07 Feb 2024




Intermediate

**No, in C#, only one catch block is executed when an exception occurs in a try block. **

In a try-catch statement, the control flows to the first catch block that matches the type of the thrown exception. Once the corresponding catch block is executed, the control exits the try-catch statement.

Here's a simple example:

try
{
    // Some code that might throw an exception
    int x = 0;
    int y = 10 / x; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    // This catch block will handle DivideByZeroException
    Console.WriteLine("Divide by zero error: " + ex.Message);
}
catch (Exception ex)
{
    // This catch block will handle any other exception types
    Console.WriteLine("An error occurred: " + ex.Message);
}

In this example, if a DivideByZeroException is thrown, only the first catch block will be executed. If any other exception type occurs, it will be caught by the second catch block. The control does not flow to both catch blocks simultaneously.

c-sharp
exception-handling