Skip to main content
๐Ÿ“œ WAYPOINT LESSON

try / catch: reacting to failure

โญ beginnerโณ 13 min read๐Ÿ“ Lesson 50 of 85

An exception unwinds the call stack until a matching catch โ€” or crashes the program.

What an exception is

When code hits a condition it cannot fulfill โ€” int.Parse("abc"), indexing past an array's end โ€” it throws an exception object describing the failure. The runtime unwinds the call stack looking for a handler:

try
{
    int n = int.Parse("abc");   // throws FormatException
    Console.WriteLine("never runs");
}
catch (FormatException ex)
{
    Console.WriteLine($"not a number: {ex.Message}");
}
Console.WriteLine("program continues");

try marks a guarded region; catch handles a specific failure type. If nothing catches it, the program dies with the stack trace.

Catch specific, handle honestly

catch (FormatException ex) { ... }   // only this failure
catch (Exception ex) { ... }         // everything โ€” use sparingly

A broad catch (Exception) swallows bugs you didn't anticipate: typos, null refs, logic errors โ€” all invisible. Catch the specific type you can actually do something about; let the rest crash loudly during development instead of hiding.