Loading...

C# Exception Handling (try, catch, finally)

Learn how to handle exceptions in C# using try, catch, and finally blocks to manage errors safely with clear examples.

In C#, error handling is used to catch and manage unexpected situations during program execution. This prevents the program from crashing abruptly and allows you to show appropriate messages or take alternative actions. Error handling uses the try, catch, and finally blocks together.


try-catch Usage

The try block contains code that may throw an exception. If an error occurs, the catch block handles it.


try
{
    int number = int.Parse("abc"); // Invalid conversion
    Console.WriteLine("Number: " + number);
}
catch (FormatException ex)
{
    Console.WriteLine("Error: Invalid number format.");
}
// Output:
Error: Invalid number format.

Multiple catch Blocks

You can use multiple catch blocks for different error types. This allows handling each exception type differently.


try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Error: Array index out of range.");
}
catch (Exception ex)
{
    Console.WriteLine("Unexpected error: " + ex.Message);
}

finally Block

The finally block always runs, regardless of whether an error occurred or not. It is often used for cleanup operations like closing files or terminating database connections.


try
{
    Console.WriteLine("Opening file...");
    throw new Exception("File not found!");
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    Console.WriteLine("Closing file...");
}
// Output:
Opening file...
Error: File not found!
Closing file...

Throwing Custom Exceptions

You can define your own error conditions and throw exceptions using throw.


static void Divide(int a, int b)
{
    if (b == 0)
        throw new DivideByZeroException("Division by zero error!");
    Console.WriteLine("Result: " + (a / b));
}

static void Main()
{
    try
    {
        Divide(10, 0);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
}
// Output:
Error: Division by zero error!

TL;DR

  • try: Block with code that may throw exceptions.
  • catch: Handles the error when it occurs.
  • finally: Always runs, typically for cleanup.
  • throw: Used to throw custom exceptions.
  • Multiple catch blocks allow handling different exception types separately.