Multiple catch blocks in exception

In C#, you can use multiple catch blocks to handle different types of exceptions that may occur within a try block. When an exception is thrown, the catch blocks are checked in order to find a matching exception type. The first catch block that matches the type of the thrown exception will be executed, and the remaining catch blocks will be skipped.

The syntax for multiple catch blocks is as follows:


try
{
    // Code that may throw exceptions
}
catch (ExceptionType1 ex)
{
    // Code to handle exceptions of type ExceptionType1
}
catch (ExceptionType2 ex)
{
    // Code to handle exceptions of type ExceptionType2
}
// Add more catch blocks for other exception types as needed
catch (Exception ex)
{
    // Code to handle any other unhandled exceptions
}
finally
{
    // Code that will be executed regardless of whether an exception occurred or not
}

Here's an explanation of each part:

  1. 'try': The try block contains the code that may potentially throw an exception. It is the portion of code where you want to handle potential exceptions.
  2. 'catch (ExceptionType1 ex)': Each catch block specifies a particular type of exception that it can handle. If an exception of type 'ExceptionType1' is thrown, this catch block will be executed. The caught exception will be available as 'ex', and you can use it to extract information about the exception and handle it appropriately.
  3. 'catch (ExceptionType2 ex)': You can have multiple catch blocks, each handling a different type of exception. In this example, the second catch block handles exceptions of type 'ExceptionType2'.
  4. 'catch (Exception ex)': It is common to have a catch block that handles the base class Exception. This block will catch any unhandled exceptions or exceptions that do not match the specific types mentioned in previous catch blocks.
  5. 'finally': The finally block is optional, and it contains code that will always be executed, regardless of whether an exception occurred or not. It is useful for cleanup operations that need to happen, such as releasing resources or closing connections.

When an exception is thrown within the try block, the CLR (Common Language Runtime) searches for a matching catch block based on the type of the thrown exception. If a match is found, the corresponding catch block's code is executed. If no match is found, the CLR will continue searching through any subsequent catch blocks or execute the code in the finally block (if one is present). If there is no catch block for the specific exception type and no finally block, the program will terminate with an unhandled exception.

Keep in mind that catch blocks are checked in the order they appear in the code. Therefore, it's essential to place more specific exception types before more general ones to ensure the correct catch block is executed for a given exception type.

Here's a C# example that demonstrates the use of multiple catch blocks to handle different types of exceptions:


using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] arr = new int[5] { 34, 45, 12, 25, 10 };
            int index = 10; // Accessing an invalid index to throw an exception
            Console.WriteLine("Value at index {0}: {1}", index, arr[index]);
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Index out of range: {0}", ex.Message);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Divide by zero error: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unknown error occurred: {0}", ex.Message);
        }
        finally
        {
            Console.WriteLine("Finally block executed.");
        }
    }
}

In this example, the 'Main' method attempts to access an element at an invalid index in the array 'arr', which will throw an 'IndexOutOfRangeException'. The code also contains multiple catch blocks to handle different types of exceptions that may arise during the execution.

  1. The first catch block ('catch (IndexOutOfRangeException ex)') handles the 'IndexOutOfRangeException' specifically.
  2. The second catch block ('catch (DivideByZeroException ex)') is included as an example but will not be executed in this scenario since there is no division operation in the code.
  3. The third catch block ('catch (Exception ex)') is a catch-all block and will catch any other exception types not caught by the previous catch blocks.

When you run this program, it will catch the 'IndexOutOfRangeException', and the corresponding catch block will be executed, displaying the error message. Since there's no division operation that can cause a DivideByZeroException, that catch block will not be executed in this specific example.

The finally block is used to specify code that will always be executed, regardless of whether an exception occurred or not. In this case, it prints a message to indicate that the finally block has been executed.