C# Exceptions - Complete Guide
Introduction to Exceptions
Exceptions in C# are runtime events that disrupt the normal program flow. They provide a structured way to detect and handle errors without crashing the application.
C# uses try-catch-finally blocks for exception handling. The base class for all exceptions is System.Exception, and the .NET framework defines many specialized exception types like DivideByZeroException, FileNotFoundException, and ArgumentNullException.
Exception Handling Examples
Here are examples demonstrating different ways to handle exceptions in C#:
Example
using System;
using System.IO;
namespace ExceptionsExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Basic Try-Catch ===");
try
{
int result = Divide(10, 0);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Console.WriteLine("\n=== Multiple Catch Blocks ===");
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
string text = null;
Console.WriteLine(text.Length);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Index error: {ex.Message}");
}
catch (NullReferenceException ex)
{
Console.WriteLine($"Null reference error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}
Console.WriteLine("\n=== Finally Block ===");
FileStream fileStream = null;
try
{
fileStream = new FileStream("test.txt", FileMode.Open);
Console.WriteLine("File opened successfully");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.Message}");
}
finally
{
fileStream?.Close();
Console.WriteLine("File stream closed (finally block)");
}
Console.WriteLine("\n=== Custom Exceptions ===");
try
{
ValidateAge(15);
}
catch (InvalidAgeException ex)
{
Console.WriteLine($"Custom exception: {ex.Message}");
Console.WriteLine($"Invalid age: {ex.InvalidAge}");
}
Console.WriteLine("\n=== Exception Properties ===");
try
{
ThrowSampleException();
}
catch (Exception ex)
{
Console.WriteLine($"Message: {ex.Message}");
Console.WriteLine($"Stack Trace: {ex.StackTrace}");
Console.WriteLine($"Source: {ex.Source}");
Console.WriteLine($"Target Site: {ex.TargetSite}");
if (ex.InnerException != null)
{
Console.WriteLine($"Inner Exception: {ex.InnerException.Message}");
}
}
Console.WriteLine("\n=== Using Blocks ===");
using (var resource = new ManagedResource())
{
resource.DoSomething();
Console.WriteLine("Resource used inside using block");
}
Console.WriteLine("\n=== Exception Filtering (when) ===");
try
{
ProcessInput(-5);
}
catch (ArgumentException ex) when (ex.ParamName == "value")
{
Console.WriteLine($"Parameter error: {ex.Message}");
}
Console.WriteLine("\n=== Throw Expressions ===");
try
{
string name = GetName(null);
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"Throw expression error: {ex.Message}");
}
Console.WriteLine("\nProgram continues after exception handling...");
}
static int Divide(int a, int b) => a / b;
static void ValidateAge(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Age must be 18 or older", age);
}
}
static void ThrowSampleException()
{
try
{
object obj = null;
obj.ToString();
}
catch (Exception ex)
{
throw new ApplicationException("An error occurred in processing", ex);
}
}
static void ProcessInput(int value)
{
if (value < 0)
{
throw new ArgumentException("Value cannot be negative", "value");
}
}
static string GetName(string name)
{
return name ?? throw new ArgumentNullException(nameof(name), "Name cannot be null");
}
}
public class InvalidAgeException : Exception
{
public int InvalidAge { get; }
public InvalidAgeException(string message, int invalidAge) : base(message)
{
InvalidAge = invalidAge;
}
}
public class ManagedResource : IDisposable
{
public void DoSomething() => Console.WriteLine("Doing something with resource...");
public void Dispose() => Console.WriteLine("Resource disposed cleanly");
}
}
Output
=== Basic Try-Catch === Error: Attempted to divide by zero. === Multiple Catch Blocks === Index error: Index was outside the bounds of the array. === Finally Block === File not found: Could not find file 'test.txt'. File stream closed (finally block) === Custom Exceptions === Custom exception: Age must be 18 or older Invalid age: 15 === Exception Properties === Message: An error occurred in processing Stack Trace: [stack trace details] Source: ExceptionsExample Target Site: Void ThrowSampleException() Inner Exception: Object reference not set to an instance of an object. === Using Blocks === Doing something with resource... Resource used inside using block Resource disposed cleanly === Exception Filtering (when) === Parameter error: Value cannot be negative === Throw Expressions === Throw expression error: Name cannot be null Program continues after exception handling...