Exception handling
Exception handling decides what happens when something goes wrong at run time: catch the problem where you can handle it, clean up resources every time, and keep the stack trace intact instead of letting one bad input crash the whole app.
23.1 Why is it used?
- Real users type bad input ("5a" as a quantity) all the time.
- An exception is an object carrying the error type, message and stack trace.
- It travels up the call stack; if no code catches it, the runtime shuts down the whole app.
- try/catch gives a place to catch it and respond (show a clear message, retry, log).
23.2 The bug: one input, app crash
C#
string input = "5a";int qty = int.Parse(input); Console.WriteLine($"Quantity: {qty}");Console.WriteLine("Order saved");Output
$ dotnet run Qty.csUnhandled exception.System.FormatException: The input string '5a' was not in a correct format. at System.Int32.Parse(String s) at Program.<Main>$(String[] args) in Qty.cs:line 223.3 try and catch
- Put the risky code inside try.
- If Parse fails, control jumps straight to the matching catch (here only FormatException).
- ex.Message gives the original error text; code after the try/catch keeps running.
C#
string input = "5a"; try{ int qty = int.Parse(input); Console.WriteLine($"Quantity: {qty}");}catch (FormatException ex){ Console.WriteLine($"Invalid input: {input}"); Console.WriteLine(ex.Message);} Console.WriteLine("App still running");Output
$ dotnet run TryCatch.csInvalid input: 5aThe input string '5a' was not in a correct format.App still running23.4 finally: cleanup every time
- finally runs in every case: try succeeds, catch runs, or a return happens in between.
- Use it to close connections, files, locks.
- The using statement does this cleanup automatically; under the hood it is a try/finally calling Dispose.
C#
Console.WriteLine(Save("5a")); static string Save(string input){ Console.WriteLine("DB connection open"); try { return $"Saved {int.Parse(input)}"; } catch (FormatException) { return "Invalid quantity"; } finally { Console.WriteLine("DB closed"); }}Output
$ dotnet run Finally.csDB connection openDB closedInvalid quantityCheckpoint: with Save("3") the return value is ready, but finally still runs before the method exits, so DB closed prints before Saved 3.
Output
$ dotnet run Finally.csDB connection openDB closedSaved 323.5 Custom exception
- Built-in exceptions do not carry domain details such as why a payment failed.
- Inherit from Exception, end the name with Exception, pass message and inner exception to the base.
- Add extra properties (Reason) for the catcher to use.
C#
static void Pay(decimal amount, decimal balance){ if (amount > balance) throw new PaymentFailedException( "LOW_BALANCE", $"Need {amount - balance} more");} class PaymentFailedException( string reason, string message, Exception? inner = null) : Exception(message, inner){ public string Reason { get; } = reason;}23.6 when filter: a catch with a condition
- catch (...) when (condition) matches only if the condition is true; otherwise the next catch is checked.
- Order matters: the specific catch comes first, the general one after.
- A filter that is false does not unwind the stack, so the original context is kept.
C#
try{ Pay(amount: 2500, balance: 1000);}catch (PaymentFailedException ex) when (ex.Reason == "LOW_BALANCE"){ Console.WriteLine($"Add money: {ex.Message}");}catch (PaymentFailedException ex){ Console.WriteLine($"Failed: {ex.Reason}");}Output
$ dotnet run Payment.csAdd money: Need 1500 more- Step 1
1.A method throws: exception object created
- Step 2
2.Runtime walks up the call stack
- Step 3
3.Each catch is checked: type + when filter
- Step 4
4.Match found: finally blocks in between run (cleanup)
- Step 5
5.Matching catch block runs
- Step 6
6.No match anywhere: unhandled, app crashes
23.7 throw vs throw ex
C#
Checkout("5a"); static void Checkout(string input){ try { ParseQty(input); } catch (FormatException ex) { Console.WriteLine("Log: bad quantity"); throw ex; }} static int ParseQty(string s) => int.Parse(s);Output
$ dotnet run ThrowEx.csThrowEx.cs(9,9): warning CA2200: Re-throwing caught exception changes stack informationLog: bad quantityUnhandled exception.System.FormatException: The input string '5a' was not in a correct format. at Program...Checkout(String input) in ThrowEx.cs:line 9 at Program.<Main>$(String[] args) in ThrowEx.cs:line 1- throw ex rethrows as if fresh: the trace starts at line 9 and ParseQty / Int32.Parse are lost.
- Just throw; rethrows the same exception with its original trace (reaches ParseQty line 13 and Int32.Parse).
- To add context: throw new SomeException("context", ex) so the original is kept as InnerException.
C#
static void Checkout(string input){ try { ParseQty(input); } catch (FormatException) { Console.WriteLine("Log: bad quantity"); throw; }}| Form | Stack trace | Use when |
|---|---|---|
| throw; | Original trace kept | Log and pass the same error on |
| throw ex; | Reset to the rethrow line (CA2200) | Never |
| throw new X(msg, ex); | New exception, original in InnerException | Adding domain context |
23.8 Common mistakes
- catch (Exception) in every method: it hides the error and the app runs on with wrong data, worse than a crash.
- Empty catch blocks that swallow errors silently.
- throw ex instead of throw.
- Using exceptions for expected cases like user input instead of int.TryParse.
- Catch only where you can handle; let the rest reach one global handler (ASP.NET Core, later).
23.9 Best practices
- Catch specific exceptions; never leave an empty catch.
- Rethrow with throw; wrap with an inner exception to add context.
- Clean up with finally or using.
- For expected input, use TryParse-style methods instead of exceptions.
- Name custom exceptions ...Exception.
23.10 Interview tips
- Risky code goes in try; catch only the specific exceptions you can actually handle.
- finally (or using) guarantees cleanup, and runs even when try or catch returns.
- throw keeps the stack trace, throw ex resets it (CA2200).
- Custom exceptions for domain errors, when filters to catch by condition.
- Do not catch everywhere: unhandled errors should reach a global handler and be logged.