How to use try catch finally in C#
The try-catch-finally block in C# handles exceptions. Code in the try block executes first. If an exception occurs, control jumps to the matching catch block. The finally block always executes, whether an exception occurred or not.
You can catch specific exception types or use a general Exception catch-all. Multiple catch blocks allow handling different exceptions differently, ordered from most specific to most general.
The finally block is ideal for cleanup operations like closing files, disposing resources, or releasing locks, ensuring they happen regardless of exceptions.
Basic try-catch
// Basic try-catch
try
{
int result = Divide(10, 0);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: Cannot divide by zero - {ex.Message}");
}
static int Divide(int a, int b)
{
return a / b;
}Using try-catch-finally for Cleanup
The finally block always executes, making it perfect for cleanup operations like closing files or releasing resources.
// Try-catch-finally
try
{
Console.WriteLine("Opening file...");
ProcessFile("data.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("Cleanup: Always executes");
}
static void ProcessFile(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("File does not exist", path);
}
}Multiple Catch Blocks
Order catch blocks from most specific to most general exception types. Specific exceptions are checked first.
// Multiple catch blocks
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Index error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}Throwing and Catching Custom Exceptions
// Rethrowing exceptions
try
{
ValidateAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Validation failed: {ex.Message}");
}
static void ValidateAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative", nameof(age));
}
}