Catching Exceptions


The order in which exceptions are caught is significant when base and derived exception classes are involved. This is because a catch for a base class will also match any of its derived classes. Given that Exception is the base class of all exceptions, catching this type catches all possible exceptions. Clearly catching Exception should be the last catch clause in the try-catch statement and exception classes that are derived should precede this clause. Generally, the classes higher in the inheritance hierarchy should precede those lower in the hierarchy. The next program shows how this is done.

// Exception15 - Catch Exception Hierarchies

using System;

class ExceptionA : ApplicationException
{
    public ExceptionA() : base("This is ExceptionA") { }

    public ExceptionA(string s) : base(s) { }
}

class ExceptionB : ExceptionA
{
    public ExceptionB() : base("This is ExceptionB") { }

    public ExceptionB(string s) : base(s) { }
}

class Program
{
    static void Main()
    {
        for (int i = 0; i < 3; i++)
            try
            {
                if (i == 0)
                    throw new ExceptionB();
                else if (i == 1)
                    throw new ExceptionA();
                else
                    throw new Exception();
            }
            catch (ExceptionB e)
            {
                Console.WriteLine(e);
            }
            catch (ExceptionA e)
            {
                Console.WriteLine(e);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
    }
}

The output of the program is shown below.

ExceptionB: This is ExceptionB
   at Program.Main() in d:\CSharp\Projects\Exception15\Program.cs:line 27
ExceptionA: This is ExceptionA
   at Program.Main() in d:\CSharp\Projects\Exception15\Program.cs:line 29
System.Exception: Exception of type 'System.Exception' was thrown.
   at Program.Main() in d:\CSharp\Projects\Exception15\Program.cs:line 31

ExceptionB is at the top of the hierarchy so it is caught first. ExceptionA is a base class of ExceptionB and it is caught next. Then all exceptions are caught by catching Exception.