C# Handling multiple exceptions

In C#, you can create and handle multiple exceptions using multiple catch blocks or custom exception classes. Each catch block can handle a specific type of exception, allowing you to handle them in a customized manner.

1. Handling Multiple Exceptions with Multiple catch Blocks


using System;

class MyProgram
{
    static void Main()
    {
        try
        {
            // Example code that may throw different exceptions
            int[] numbers = new int[2];
            numbers[3] = 20;  // This will throw an IndexOutOfRangeException
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Caught an IndexOutOfRangeException: " + ex.Message);
        }
        catch (NullReferenceException ex)
        {
            Console.WriteLine("Caught a NullReferenceException: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught a general Exception: " + ex.Message);
        }
    }
}

Output:

Caught an IndexOutOfRangeException: Index was outside the bounds of the array.

Explanation:

  • First catch block: Handles the IndexOutOfRangeException, which occurs when you attempt to access an element outside the bounds of an array.
  • Second catch block: Handles the FormatException, which occurs when you try to parse a string into a number but the string isn’t in a valid format.
  • General catch block: If the exception doesn’t match either of the specific exceptions above, it falls back to this block and handles all other exceptions.

2. Handling Multiple Exceptions in One catch Block (C# 6 and Later)

In C# 6 and later, you can handle multiple exception types in a single catch block using the | (OR) operator. This allows you to handle multiple exceptions in a similar way without needing multiple catch blocks.


using System;

class MyProgram
{
    static void Main()
    {
        try
        {
            string name = "John";
            int number = int.Parse(name);  // This will throw a FormatException
        }
        catch (FormatException | InvalidOperationException ex)
        {
            Console.WriteLine("Caught a FormatException or InvalidOperationException: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught a general Exception: " + ex.Message);
        }
    }
}

Output:

Caught a FormatException or InvalidOperationException: Input string was not in a correct format.

Explanation:

  1. The catch block uses the | operator to catch both FormatException and InvalidOperationException exceptions.
  2. If either of these exceptions is thrown, the catch block will execute.
  3. The second catch block is a fallback for all other exceptions.

3. Multiple exceptions with the when clause

In C#, you can use multiple exceptions with the when clause in a try-catch block to filter exceptions based on certain conditions. The when clause allows you to apply a condition to a specific exception type, and only catch the exception if the condition evaluates to true.


using System;

class MyProgram
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            // Try to access an invalid index
            Console.WriteLine(numbers[10]);
        }
        catch (IndexOutOfRangeException ex) when (ex.Message.Contains("Index"))
        {
            Console.WriteLine("Caught an IndexOutOfRangeException: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught a general exception: " + ex.Message);
        }
    }
}

Output:

Caught an IndexOutOfRangeException: Index was outside the bounds of the array.

4. Handling Multiple Exception Types with Custom Exception Class

This example demonstrates handling both built-in exceptions and a custom exception that you define.


using System;

class CustomException : Exception
{
    public CustomException(string message) : base(message) { }
}

class MyProgram
{
    static void Main()
    {
        try
        {
            // Simulating a custom exception
            throw new CustomException("This is a custom exception!");
        }
        catch (CustomException ex)
        {
            Console.WriteLine("Custom Exception caught: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General Exception caught: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Exception handling complete.");
        }
    }
}

Output:

Custom Exception caught: This is a custom exception!
Exception handling complete.