Programming isn't just about the "Happy Path." Defensive Programming is the art of ensuring your code fails loudly and safely the second something goes wrong. In C#, we use Guard Clauses to validate inputs and Exceptions to handle the unavoidable chaos of the runtime.
Instead of wrapping your whole function in a massive if block, "Guard" the entry point of your method. Fail early, fail fast.
public void ProcessPayment(decimal amount)
{
// Modern Guard Clause (.NET 8 style)
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
// Traditional Guard
if (string.IsNullOrWhiteSpace(userName))
throw new ArgumentException("Name cannot be empty.");
// Execution continues only if inputs are PERFECT
ExecuteTransaction(amount);
}
You can catch an exception ONLY if a specific secondary condition is met. This keeps your catch blocks incredibly clean.
try
{
await _api.CallAsync();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
// Log specifically for 404s
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
{
// Handle Login Redirects
}
NEVER write catch (Exception ex) { } (the "Empty Catch"). This is the most dangerous line of code in history—it silences errors, making bugs impossible to find. Always catch the specific exception you expect.
Q: "Why is 'throw ex;' considered a cardinal sin compared to just writing 'throw;' inside a catch block?"
Architect Answer: "The difference is the Stack Trace preservation. When you write `throw ex;`, you are telling the CLR to restart the exception cycle. This physically overwrites the Stack Trace, making it look like the error originated exactly at that line of code. When you write `throw;`, you are actually 'Re-throwing' the original exception, preserving the entire historical stack trace back to the original failing line in the deep library. For debugging production systems, preserving that original stack trace is the difference between a 5-minute fix and a 2-day investigation."