Light Mode Image

C# Multiple Try-Catch

You can use multiple try-catch blocks to handle different types of exceptions in a structured manner. Each try block is followed by one or more catch blocks that specify the type of exception to catch and the code to execute when that specific exception occurs.

 

Here's an example of using multiple try-catch blocks.

using System;

class Program
{
    static void Main()
    {
        try
        {
            // Code that may throw exceptions
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[10]);  // This line will throw an IndexOutOfRangeException
        }
        catch (IndexOutOfRangeException ex)
        {
            // Handle specific exception
            Console.WriteLine($"IndexOutOfRangeException: {ex.Message}");
        }
        catch (DivideByZeroException ex)
        {
            // Handle another specific exception
            Console.WriteLine($"DivideByZeroException: {ex.Message}");
        }
        catch (Exception ex)
        {
            // Handle any other exceptions not caught by previous catch blocks
            Console.WriteLine($"Generic Exception: {ex.Message}");
        }
        finally
        {
            // Code in the finally block will be executed regardless of whether an exception occurs or not
            Console.WriteLine("Finally block executed.");
        }

        // Rest of the program continues after handling exceptions
    }
}

 

In this example,

 

1. The first try block contains code that may throw an IndexOutOfRangeException.

 

2. The second catch block handles the IndexOutOfRangeException.

 

3. The third catch block handles a DivideByZeroException, which is not applicable to the provided code but is included for demonstration purposes.

 

4. The last catch block handles any other exceptions that were not caught by the previous catch blocks.

 

5. The finally block contains code that will be executed regardless of whether an exception occurred or not.

 

It's generally a good practice to catch specific exceptions rather than catching the general Exception class, as this allows for more precise handling of errors.