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
| Exception | Cause |
|---|---|
NullReferenceException | Using an object reference that is null |
IndexOutOfRangeException | Array index out of bounds |
FormatException | Parsing a non-numeric string |
FileNotFoundException | File does not exist |
OverflowException | Numeric overflow in checked context |
InvalidOperationException | Method 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;
}