11. Exception Handling

An exception is an object that represents an error at run time, such as dividing by zero, parsing bad text, a missing file or using a null reference. When one is thrown, normal execution stops and .NET looks for a matching catch block up the call stack; if none is found the program crashes. All exceptions derive from System.Exception. Put risky code in a try block, handle specific errors in catch blocks (most specific first, general Exception last), and use finally for cleanup that must always run, whether or not an error happened.

Common exceptions: FormatException (bad text conversion), ArgumentException, ArgumentNullException and ArgumentOutOfRangeException (bad arguments), InvalidOperationException (wrong object state), NullReferenceException, IndexOutOfRangeException, KeyNotFoundException, DivideByZeroException, OverflowException, InvalidCastException, FileNotFoundException and other IOExceptions. Use throw to raise your own exceptions, guard clauses to validate arguments early, and custom exception classes (derive from Exception) for domain-specific errors. Exception filters (catch ... when (condition)) choose a handler by condition.

Use throw; (not throw ex;) to rethrow while keeping the original stack trace, wrap a lower-level error as the InnerException of a new one to add context, and use using statements or declarations to dispose of resources such as files, streams and database connections automatically (they implement IDisposable). Exceptions are for exceptional situations: validate input with TryParse or if checks instead of using exceptions for normal flow.

Key points to remember

  • Order catch blocks from the most specific to the most general. The compiler reports an error if a general catch comes before a specific one.
  • finally runs even if the try block returns or throws. Do not put return or throw inside finally.
  • Never leave an empty catch block: swallowing exceptions hides bugs. At least log the problem or rethrow.
  • Catch only what you can handle. Let unexpected errors travel up to one central place (in ASP.NET Core, an exception-handling middleware) that logs them and returns a friendly message.
  • Exception properties: Message (what happened), StackTrace (where), InnerException (the original cause), and GetType().Name (the kind).
  • throw; keeps the stack trace. throw ex; resets it and hides where the error started.
  • Throwing is slow compared to normal code. Use int.TryParse, Dictionary.TryGetValue and null checks for expected situations.
  • Use ArgumentNullException.ThrowIfNull(x) and ArgumentOutOfRangeException checks at the start of public methods.
  • Custom exceptions should end with Exception, derive from Exception, and usually provide message and inner-exception constructors.
  • Don't show raw exception messages or stack traces to end users of a web app; log them instead.

Example 1: try / catch / finally

C#
try
{
    int x = int.Parse("abc");
}
catch (FormatException ex)
{
    Console.WriteLine("Bad number");
}
finally
{
    Console.WriteLine("Done");
}
Show output Output
Bad number
Done

Example 2: Several catch blocks

C#
string?[] tests = { "12", "abc", null };
foreach (var t in tests)
{
    try
    {
        int n = int.Parse(t!);
        Console.WriteLine(n * 2);
    }
    catch (FormatException)
    {
        Console.WriteLine("Not a number");
    }
    catch (ArgumentNullException)
    {
        Console.WriteLine("Null value");
    }
    catch (Exception ex)                 // general handler goes last
    {
        Console.WriteLine("Other: " + ex.Message);
    }
}
Show output Output
24
Not a number
Null value

Example 3: Common exceptions and what causes them

C#
int[] a = { 1 };
int zero = 0;
string? s = null;

Try(() => Console.WriteLine(a[3]));
Try(() => Console.WriteLine(10 / zero));
Try(() => Console.WriteLine(s!.Length));
Try(() => Convert.ToInt32("x"));
Try(() => new List<int>().First());
Try(() => { var v = new Dictionary<string, int>()["k"]; });
Try(() => { object o = "text"; int i = (int)o; });

static void Try(Action action)
{
    try { action(); }
    catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }
}
Show output Output
IndexOutOfRangeException
DivideByZeroException
NullReferenceException
FormatException
InvalidOperationException
KeyNotFoundException
InvalidCastException

Example 4: Throwing exceptions

C#
static void SetAge(int age)
{
    if (age < 0) throw new ArgumentException("Age cannot be negative");
}

try { SetAge(-1); }
catch (ArgumentException ex) { Console.WriteLine(ex.Message); }
Show output Output
Age cannot be negative

Example 5: Guard clauses

C#
static void Register(string? name, int age)
{
    ArgumentNullException.ThrowIfNull(name);
    if (age < 0 || age > 120)
        throw new ArgumentOutOfRangeException(nameof(age), "Age must be 0-120");
    Console.WriteLine($"Registered {name}");
}

try { Register(null, 20); }
catch (ArgumentNullException ex) { Console.WriteLine(ex.ParamName); }

try { Register("Ann", 200); }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.ParamName); }

Register("Ann", 30);
Show output Output
name
age
Registered Ann

Example 6: Exception filters (when)

C#
static void Run(string mode)
{
    try { throw new InvalidOperationException(mode); }
    catch (InvalidOperationException ex) when (ex.Message == "retry")
    {
        Console.WriteLine("Retrying...");
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine("Failed: " + ex.Message);
    }
}

Run("retry");
Run("fatal");
Show output Output
Retrying...
Failed: fatal

Example 7: Custom exceptions

C#
try
{
    Withdraw(100, 500);
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine($"{ex.Message} (short by {ex.Shortfall})");
}

static void Withdraw(decimal balance, decimal amount)
{
    if (amount > balance)
        throw new InsufficientFundsException(amount - balance);
}

class InsufficientFundsException : Exception
{
    public decimal Shortfall { get; }
    public InsufficientFundsException(decimal shortfall)
        : base("Insufficient funds")
    {
        Shortfall = shortfall;
    }
}
Show output Output
Insufficient funds (short by 400)

Example 8: Rethrowing and wrapping exceptions

C#
try
{
    try
    {
        int.Parse("x");
    }
    catch (FormatException ex)
    {
        // add context, keep the original as InnerException
        throw new InvalidOperationException("Could not load settings", ex);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.InnerException?.GetType().Name);
}

try
{
    try { throw new Exception("boom"); }
    catch (Exception)
    {
        Console.WriteLine("Logging the error");
        throw;                       // rethrow with the original stack trace
    }
}
catch (Exception ex)
{
    Console.WriteLine("Caught again: " + ex.Message);
}
Show output Output
Could not load settings
FormatException
Logging the error
Caught again: boom

Example 9: finally always runs

C#
Console.WriteLine(Test());

static string Test()
{
    try
    {
        return "try";
    }
    finally
    {
        Console.WriteLine("finally runs first");
    }
}
Show output Output
finally runs first
try

Example 10: using statements and IDisposable

C#
using (var r = new Resource("A"))
{
    Console.WriteLine("Working");
}                                         // A is disposed here

using var r2 = new Resource("B");         // disposed at the end of the scope
Console.WriteLine("End of scope");

class Resource : IDisposable
{
    private readonly string _name;
    public Resource(string name) { _name = name; Console.WriteLine($"Open {name}"); }
    public void Dispose() => Console.WriteLine($"Close {_name}");
}
Show output Output
Open A
Working
Close A
Open B
End of scope
Close B

Example 11: Avoiding exceptions with TryParse

C#
string[] inputs = { "42", "4x2", "", "-7" };
foreach (string text in inputs)
{
    if (int.TryParse(text, out int value))
        Console.WriteLine($"OK: {value}");
    else
        Console.WriteLine($"Invalid: '{text}'");
}
Show output Output
OK: 42
Invalid: '4x2'
Invalid: ''
OK: -7