Junior
Is there a difference in the order of catch blocks in a try-catch construct?
sobes.tech AI
Answer from AI
Yes, there is a difference. catch blocks are checked sequentially from top to bottom.
More specific exceptions should come first, and more general ones last. If a catch block for a more general exception is placed above a block for a more specific one, the code for handling the specific exception will never be executed because the exception will be caught by the more general block.
For example:
try
{
// Some code that may throw exceptions
}
catch (DivideByZeroException ex) // More specific exception
{
// Handling division by zero
Console.WriteLine($"Error: division by zero. {ex.Message}");
}
catch (Exception ex) // More general exception
{
// Handling any other exception
Console.WriteLine($"An error occurred: {ex.Message}");
}
If you swap the places of catch (Exception ex) and catch (DivideByZeroException ex), then when a DivideByZeroException occurs, it will be caught by the first catch (Exception ex) block, and the code for handling division by zero will never be executed.