1.20 — Exception Handling¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.19 Indexers and operators · Next: 1.21 IDisposable
Markers: 🔥 ⚠️ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
throw;keeps the original stack trace.throw ex;destroys it. This is the single most-asked question in this topic.finallyalways runs, whether an exception happened or not. That is what makes cleanup reliable.- Only catch what you can actually do something about. Catching everything and carrying on quietly is worse than crashing.
The concept¶
An exception is how a method says "I cannot do what you asked, and I cannot carry on."
The important idea is that exceptions travel upwards. If a method throws and does not catch it, the exception passes to whoever called it, and then to whoever called them, all the way up until something catches it — or the program crashes.
That is deliberate and useful. It means the code that detects a problem does not have to be the code that decides what to do about it. A database method knows the connection failed; it has no idea whether the right response is to retry, show an error page, or give up.
How it works¶
The basic shapes¶
try
{
var result = DoRiskyThing();
}
catch (FileNotFoundException ex) // most specific first
{
logger.LogWarning(ex, "File missing, using defaults");
}
catch (IOException ex) // less specific
{
logger.LogError(ex, "IO problem");
throw;
}
finally
{
// ALWAYS runs — after success, after a handled exception,
// and on the way out of an unhandled one
connection.Close();
}
Catch blocks are checked top to bottom, and the first matching one wins. So more
specific exception types must come first. If you put catch (Exception) at the top,
nothing below it can ever run — and the compiler will tell you so.
throw; versus throw ex; ⚠️¶
This is the most-asked question in the whole topic, so it is worth being able to explain precisely.
throw ex; restarts the exception from this line. The stack trace — the list of method
calls showing where the problem actually happened — is wiped and replaced with one
starting here.
So instead of a trace pointing at the real failure five methods deep, you get one pointing at your catch block. The genuinely useful information is gone, permanently.
Bare throw; re-throws the same exception with its original stack trace intact.
If you only remember one thing from this note, remember this one.
There is a third option when you want to add context by wrapping:
catch (SqlException ex)
{
throw new OrderProcessingException($"Could not save order {id}", ex);
// ^^^^
// Pass the original as innerException — its trace is preserved inside
}
Always pass the original exception as the inner exception when wrapping. Otherwise you have thrown away the cause.
Exception filters — when¶
try { await CallApiAsync(); }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
return null; // 404 is fine, we expected it
}
catch (HttpRequestException ex) when (ex.StatusCode >= HttpStatusCode.InternalServerError)
{
throw new UpstreamUnavailableException("The API is down", ex);
}
A filter looks like it is just a condition, and you might think you could write the same
thing with an if inside the catch block. There is an important difference:
A filter is evaluated before the stack unwinds. If the filter returns false, the
exception carries on as though this catch block was never there — and the stack is
completely undisturbed. With catch + if + throw;, the runtime has already started
unwinding, which makes debugging harder and loses some information.
Filters are also very useful for conditional logging without actually handling anything:
catch (Exception ex) when (LogAndContinue(ex))
{
// never reached — LogAndContinue always returns false
}
static bool LogAndContinue(Exception ex) { Log(ex); return false; }
Custom exceptions¶
public class OrderNotFoundException(Guid orderId)
: Exception($"Order {orderId} was not found")
{
public Guid OrderId { get; } = orderId;
}
Create one when callers might reasonably want to catch that specific case. If nobody
would ever write catch (MyException), you do not need a new type — use an existing one.
Carry structured data as properties (like OrderId above) rather than only putting it in
the message. That way a handler can use the value, and your logging can record it as a
proper field rather than text.
What not to do¶
// 1. Swallowing — the worst thing in this file
try { DoWork(); }
catch { }
// The problem still happened. You just made it invisible.
// Someone will spend a day debugging this.
// 2. Catching everything at the wrong level
try { DoWork(); }
catch (Exception ex) { logger.LogError(ex, "error"); }
// Now the caller thinks it worked. Data is silently wrong.
// 3. Using exceptions for normal control flow
try { var user = GetUser(id); }
catch (NotFoundException) { user = null; }
// "Not found" is a normal outcome, not an exceptional one.
// Return null or use a Try pattern — exceptions are SLOW
// (roughly thousands of times slower than a normal return).
Exceptions in ASP.NET Core¶
You should almost never wrap individual controller actions in try/catch. Instead you handle exceptions once, globally:
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
: IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext context, Exception ex, CancellationToken ct)
{
logger.LogError(ex, "Unhandled exception on {Path}", context.Request.Path);
var problem = ex switch
{
OrderNotFoundException => new ProblemDetails { Status = 404, Title = "Not found" },
ValidationException => new ProblemDetails { Status = 400, Title = "Invalid request" },
UnauthorizedAccessException=> new ProblemDetails { Status = 403, Title = "Forbidden" },
_ => new ProblemDetails { Status = 500, Title = "Server error" }
};
context.Response.StatusCode = problem.Status!.Value;
await context.Response.WriteAsJsonAsync(problem, ct);
return true;
}
}
Notice the 500 case gives no detail. Never send exception messages or stack traces to a client — they leak table names, file paths, and library versions that help an attacker. Log the detail; return something generic. See 5.12 and 17.1.
Code¶
A method that handles exceptions well — notice how little it catches:
public async Task<Order> PlaceOrderAsync(CreateOrderRequest request, CancellationToken ct)
{
// Validate up front. Do NOT use exceptions to check normal input.
if (request.Lines.Count == 0)
throw new ArgumentException("Order must have at least one line", nameof(request));
await using var transaction = await _db.Database.BeginTransactionAsync(ct);
try
{
var order = Order.Create(request);
_db.Orders.Add(order);
await _db.SaveChangesAsync(ct);
await _payments.ChargeAsync(order.Total, ct);
await transaction.CommitAsync(ct);
return order;
}
catch (PaymentDeclinedException ex)
{
// We can genuinely handle this — roll back and convert
// into something the caller understands.
await transaction.RollbackAsync(ct);
throw new OrderRejectedException(request.CustomerId, ex);
}
// Note: no catch(Exception). Anything else goes up to the
// global handler, and 'await using' still rolls the transaction back.
}
Two design points worth stating in an interview:
- The only thing caught is the one case this method can actually do something about.
- The transaction is cleaned up by
await using, not by afinallyblock. Disposal is more reliable and less code. See 1.21.
Interview questions¶
Q: What is the difference between throw; and throw ex;?
throw; re-throws the current exception and keeps its original stack trace, so you can
still see where the problem actually happened. throw ex; throws the exception object
again but resets the stack trace to start at that line, which destroys the information
about the real origin. So throw ex; is almost always a bug — it turns a useful error
report into a useless one. If you want to add context, throw a new exception and pass the
original as the inner exception, which keeps the original trace nested inside.
Q: When does the finally block run?
Always, in every normal path — after the try block succeeds, after a catch block handles
something, and while an unhandled exception is passing through on its way up. That is what
makes it the right place for cleanup. The exceptions to "always" are extreme:
Environment.FailFast, a stack overflow, or the process being killed. In modern C# you
usually do not write finally for cleanup anyway — using and await using do it more
reliably and with less code.
Q: What are exception filters and why use them over an if inside the catch?
A filter is a when clause on a catch block. The key difference from an if inside the
block is timing: the filter runs before the stack unwinds. If it returns false, the
exception continues on as if that catch block did not exist, and the stack is completely
undisturbed — which means better debugging information. With catch-then-check-then-rethrow,
unwinding has already begun. Filters are also useful for logging without handling, by
calling a logging method that always returns false.
Q: Should you catch Exception?
Very rarely, and only at the top of the application — a global handler in ASP.NET Core, or
the main loop of a background service — where the job is to log it and return a sensible
response rather than crash the whole process. Everywhere else, catching Exception means
you are claiming you can handle problems you have not thought about, including ones like
out-of-memory that you certainly cannot. The rule I use is: only catch what you can
genuinely do something about, and let everything else reach the one place that is designed
to deal with it.
Traps ⚠️¶
throw ex;wipes the stack trace. Use barethrow;.catch { }with an empty body hides real failures. If you genuinely intend to ignore something, log it and write a comment explaining why.- Exceptions are slow. Roughly thousands of times slower than a normal return. Never use them for expected outcomes like "not found" or "invalid input".
- Catch order matters. Specific types first.
catch (Exception)at the top makes everything below unreachable. - Never send exception details to a client. Messages and stack traces leak internal structure that is useful to an attacker.
OperationCanceledExceptionis normal, not an error. When a request is cancelled you will see it, and logging it as an error creates noise. See 2.14.- Exceptions inside a
finallyblock replace the original one. The real error disappears. Keepfinallyblocks simple and non-throwing. - An unobserved exception in an
async voidmethod crashes the process. See 2.15.
Related¶
- 1.21 IDisposable —
usinginstead offinally - 1.17 Pattern matching — switching on exception types
- 2.16 Async exceptions — how it changes with
await - 5.11 Exception middleware — handling globally
- 5.12 IExceptionHandler — the modern approach
- 10.8 ProblemDetails — the standard error response shape