C Sharp

Catching Multiple Exception Types

In various situations, you might want a try block to catch different exception types. For example, a given method might be documented as throwing several different exception types, or you might have several method calls in a single try block where each method being called is documented as being able to throw a different exception type. This is handled by adding a catch block for each type of exception that your code needs to handle: -

try
{
    Foo(); // Can throw FooException.
    Bar(); // Can throw BarException.
}
catch(FooException e)
{
    // Handle the error.
}
catch(BarException e)
{
    // Handle the error.
}
catch(Exception e)
{
}

Each exception type can now be handled with its distinct catch block (and error-handling code). However, one extremely important detail here is the fact that the base class is handled last. Obviously, because all exceptions are derived from System.Exception, if you were to place that catch block first, the other catch blocks would be unreachable. To that extent, the following code would be rejected by the compiler: -

try
{
    Foo(); // Can throw FooException.
    Bar(); // Can throw BarException.
}
catch(Exception e)
{
    // ***ERROR - THIS WON'T COMPILE
}
catch(FooException e)
{
    // Handle the error.
}
catch(BarException e)
{
    // Handle the error.
}