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.
C# Example Code
using System;
using System.IO;
public class TryCatchFinally
{
public static void Main(string[] args)
{
// 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}");
}
// 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");
}
// 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}");
}
// Rethrowing exceptions
try
{
ValidateAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Validation failed: {ex.Message}");
}
}
static int Divide(int a, int b)
{
return a / b;
}
static void ProcessFile(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("File does not exist", path);
}
}
static void ValidateAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative", nameof(age));
}
}
}