Back to results for “Exception Handling”
C# › Exception Handling

How does a try/catch block work in C#, and what happens if no matching catch clause exists?

Beginner

Answer

Code in the try block runs normally; if it throws, execution jumps immediately to the FIRST matching catch clause (matched by exception type, checked top to bottom) — if no catch clause matches the thrown exception's type, the exception propagates up the call stack, potentially crashing the program if never caught anywhere.
try {
  int result = 10 / int.Parse("0");
} catch (DivideByZeroException ex) {
  Console.WriteLine($"Division error: {ex.Message}");
} catch (FormatException ex) {
  Console.WriteLine($"Format error: {ex.Message}");
}
Real-world example Gracefully handling a parsing error or division-by-zero condition instead of letting the application crash.

Common follow-ups: What happens if you put a more general exception type's catch clause BEFORE a more specific one?