C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Try Catch Finally

C# Try Catch Finally

C# uses try, catch, and finally blocks to handle exceptions — preventing runtime crashes and allowing clean recovery.

1 - Basic try / catch

try
{
    int[] arr = { 1, 2, 3 };
    Console.WriteLine(arr[10]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine($"Array error: {ex.Message}");
}

2 - Multiple catch Blocks

try
{
    string input = Console.ReadLine();
    int number   = int.Parse(input);
    int result   = 100 / number;
    Console.WriteLine($"Result: {result}");
}
catch (FormatException)
{
    Console.WriteLine("Please enter a valid number.");
}
catch (DivideByZeroException)
{
    Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex) // catch-all
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}

3 - finally Block

StreamReader? reader = null;
try
{
    reader = new StreamReader("data.txt");
    Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException)
{
    Console.WriteLine("File not found.");
}
finally
{
    reader?.Dispose(); // always runs — even if exception occurred
}

4 - Exception Filters (C# 6+)

try { /* risky */ }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
    Console.WriteLine("Resource not found (404).");
}
catch (HttpRequestException ex)
{
    Console.WriteLine($"HTTP error: {ex.StatusCode}");
}

Note: The finally block always executes — even if there is a return inside the try, or an exception is not caught. It is the right place for cleanup code like closing files or releasing database connections.

-Tip-

C# {"id":43,"topic_id":3,"name":"C# Exception Handling","slug":"c-exception-handling","image":null,"description":"<p>Handle errors gracefully with try\/catch\/finally, custom exceptions, and filters.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":12,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: