Junior
Can C# have multiple catch blocks for exception handling?
sobes.tech AI
Answer from AI
Yes, there can be multiple catch blocks. This allows handling different types of exceptions differently.
When an exception occurs, the CLR checks the catch blocks sequentially from top to bottom, starting with the first. The first catch block whose exception type matches the thrown exception type or is its base class is executed.
try
{
// Code that may throw an exception
}
catch (ArgumentNullException ex)
{
// Handling ArgumentNullException
}
catch (IndexOutOfRangeException ex)
{
// Handling IndexOutOfRangeException
}
catch (Exception ex)
{
// Handling all other exceptions (base class Exception)
// This block is usually placed last
}
finally
{
// Code that will always execute, regardless of whether an exception was thrown
}
It is important to order catch blocks from more specific exception types to less specific (base) types. The catch (Exception ex) block should be last, as it catches all exceptions.