Junior — Middle
In what sequences can multiple catch exception handling blocks be placed?
sobes.tech AI
Answer from AI
In C#, catch blocks must be ordered from more specific exceptions to more general ones. This is because if a handler for the base exception class is placed first, the more specific blocks will simply not be reached.
For example:
try
{
// Code that may throw exceptions
}
catch (FileNotFoundException ex)
{
// Handling specific exception
}
catch (IOException ex)
{
// Handling more general exception
}
catch (Exception ex)
{
// Handling all other exceptions
}
If you change the order and place catch (Exception ex) first, the other blocks will become unreachable, and the compiler will generate an error.