Chapter 5
Exceptions and Error Handling
Most production incidents I have been called in to diagnose were not caused by an exception. They
were made worse by the way an exception was handled. An empty catch hid a failed database write
for three months. A throw ex; cut the stack trace off at the one method that didn't matter. A
generic error page told the user "Something went wrong" and told the support team nothing at all.
The archive shows how common this is. About 44,949 hand-written C# files contain at least one
catch (Exception ...) block, across 34 of the 35 engagements with C# code. About 7,558 files
contain an empty catch { }, in 29 engagements, and about 5,397 files rethrow with throw ex;, in
25 engagements. There are also 4,258 hand-written exception-handling classes spread across 29
engagements, most of them variations on "catch, log to a file, show a friendly message."
This chapter is about handling failures on purpose. It starts with the two habits that cause the
most damage (empty catches and throw ex;), then covers the few custom exceptions worth writing,
one global place to turn exceptions into proper HTTP responses, a Result type for failures that
are not exceptional at all, and a retry helper for the failures that go away on their own.
Recipes
- 5.1No Empty Catch BlocksA catch { } or catch (Exception) { } throws away the only evidence that something failed. The code carries on with half-finished work: a file that…
- 5.2
throw;Versusthrow ex;Code catches an exception, does some cleanup or logging, and rethrows it with throw ex;. The stack trace now starts at the rethrow, not at the line… - 5.3Custom Exceptions Worth HavingSome code bases have no custom exceptions, so everything is Exception("Customer not found") and callers parse messages to decide what to do. Others…
- 5.4Global Exception Handling with ProblemDetailsEvery controller action has its own try/catch that logs and returns a hand-built error object. The shapes differ between endpoints, some return HTML…
- 5.5A Result Type for Expected FailuresSome failures are part of normal business: insufficient funds, an expired coupon, a duplicate registration. Throwing exceptions for them is slow…
- 5.6Retry with Backoff (and Polly)Some failures are transient: a deadlock victim, a dropped connection, a 503 from an overloaded API, a timeout during a failover. Trying again a…
Chapter checklist
- Search for empty
catchblocks andthrow ex;, fix every one, and make CA2200 a build error. - Make sure every remaining
catchrecovers, translates with an inner exception, logs at a boundary or cleans up and rethrows. - Use
TryParseand similar checks for expected bad input instead of catching exceptions. - Define a few exceptions callers really act on (
NotFoundException,ConflictException,BusinessRuleException) and delete the ones nobody catches. - Add one
IExceptionHandlerthat returns ProblemDetails with atraceId, and remove the per-actiontry/catchblocks. - Return a
Result<T>for business outcomes that are expected, and keep exceptions for the unexpected. - Replace hand-rolled retry loops with exponential backoff plus jitter, retry only transient errors, and use Polly when you need timeouts or circuit breakers.