Exception Handling
Exception Handling
Section titled βException HandlingβWhat it means
Section titled βWhat it meansβC# handles runtime errors with try/catch/finally. Code that might fail goes in try; catch blocks handle specific exception types (checked most-specific-first); finally runs regardless of whether an exception was thrown, commonly used for cleanup. You throw exceptions with throw new SomeException(...).
Examples
Section titled βExamplesβtry{ int result = 10 / int.Parse("0");}catch (DivideByZeroException ex){ Console.WriteLine($"Math error: {ex.Message}");}catch (FormatException ex){ Console.WriteLine($"Bad input: {ex.Message}");}finally{ Console.WriteLine("Always runs, cleanup goes here");}
public decimal Withdraw(decimal balance, decimal amount){ if (amount > balance) throw new InvalidOperationException("Insufficient funds"); return balance - amount;}
// Custom exception typepublic class InsufficientFundsException : Exception{ public InsufficientFundsException(string message) : base(message) { }}Common mistake
Section titled βCommon mistakeβCatching Exception (the base type) too broadly, and worse, doing throw ex; to re-throw it β that resets the stack trace, making it look like the error originated in the catch block instead of where it actually happened.
try{ ProcessOrder(order);}catch (Exception ex){ LogError(ex); throw ex; // BAD: resets the stack trace, hides the real origin}
// Correct: `throw;` alone preserves the original stack tracecatch (Exception ex){ LogError(ex); throw; // re-throws the SAME exception with its original stack trace intact}Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
throw ex;andthrow;inside acatchblock?Answer
throw ex;resets the stack trace to the point of the re-throw, hiding where the error actually originated;throw;alone re-throws the same exception object with its original stack trace preserved. -
When does the
finallyblock execute?Answer
Always β whether thetryblock completes successfully, throws an exception, or even returns early. -
Why should
catchblocks generally target the most specific exception type possible, rather than the baseExceptionclass?Answer
Catching narrowly lets you handle each failure mode appropriately and avoids accidentally swallowing unrelated bugs that happen to also derive fromException.