Exception Handling
An exception is an object describing a failure that interrupts normal execution and "bubbles" up the call stack until something catches it. In C# it is the standard way to report an error: instead of return codes, a method throws, and the caller decides whether to handle it or let it propagate.
The whole topic rests on a few invariants that are easy to mix up. try guards risky code; exactly one catch runs — the first type match from top to bottom; finally runs regardless and is therefore where cleanup goes. On top of that: how to rethrow without losing the stack, when to define your own exception type versus reuse a built-in one, and how using turns resource release into a deterministic Dispose call. The full map lives in the layers below.
Topic map
- Exception handling —
try/catch/throw, finding a handler by type,throw;versusthrow ex;. - Multiple catch — tested top to bottom, first match wins, specific before general.
- The finally block — always runs, even after a
return; the cases where it is skipped. - Custom exceptions — deriving from
Exception, the standard constructors, domain context. - The using statement — deterministic
Disposeat scope exit, a hidden try/finally. - IDisposable — the resource-release contract and the dispose pattern.
Common traps
| Mistake | Consequence |
|---|---|
Assuming finally runs only on an exception | finally runs always — on success and even after a return |
Rethrowing with throw ex; | The stack trace is reset to the rethrow line — the true fault site is lost |
Placing catch (Exception) first | The more-specific blocks below become unreachable — a compile error |
Expecting several matching catch blocks to fire | Only the first matching handler runs, then control passes to finally |
Deriving a custom exception from ApplicationException | The class is obsolete; derive directly from Exception |
| Relying on the GC to close files and connections | The resource is held until nondeterministic finalization; use using/Dispose |
Interview relevance
Exception handling is asked to separate candidates who write only the happy path from those who think about failure. The answers are short but revealing: mixing up catch order, or claiming throw ex; preserves the stack, is a visible red flag.
Typical checks:
- The roles of
try,catch,finally, and thatfinallyalways runs. - The difference between
throw;andthrow ex;and why the former is preferred. - How one of several
catchblocks is chosen and why specific comes before general. - When to define a custom exception type versus reach for a built-in one.
- How
usingandIDisposablegive deterministic resource release.
Common wrong answer: "finally is there to catch the exception if catch did not." In fact finally catches nothing — it is about guaranteed cleanup, runs regardless of the outcome, and is bypassed only on hard process termination.