C# VS2026
Lesson 15 of 30

Exception Handling

C# in Visual Studio 2026 — a hands-on guide for developers at every level.

What are Exceptions?

An exception is a runtime error that disrupts normal program flow. In C#, exceptions are objects that inherit from System.Exception. Unhandled exceptions crash the program; handled exceptions let you recover gracefully.

try / catch / finally

try
{
    int result = 10 / 0;  // throws DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"Math error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected: {ex.Message}");
}
finally
{
    Console.WriteLine("This always runs.");
}

Common Exception Types

ExceptionCause
NullReferenceExceptionUsing an object reference that is null
IndexOutOfRangeExceptionArray index out of bounds
FormatExceptionParsing a non-numeric string
FileNotFoundExceptionFile does not exist
OverflowExceptionNumeric overflow in checked context
InvalidOperationExceptionMethod call invalid for current state

Throwing Exceptions

static int Divide(int a, int b)
{
    if (b == 0)
        throw new ArgumentException("Divisor cannot be zero", nameof(b));
    return a / b;
}

Custom Exceptions

public class InsufficientFundsException : Exception
{
    public decimal Amount { get; }
    public InsufficientFundsException(decimal amount)
        : base($"Insufficient funds: need {amount:C} more")
        => Amount = amount;
}