#868 – List Most Specific Exception Types First

When you include more than one catch blocks as part of a try-catch statement, you must list the most specific exception types first.  When an exception occurs, the type of the exception object is compared with the type of each catch block in order, starting with the first.  When the type exception parameter in the catch block matches or is a parent type of the type of the exception, that catch block will “catch” the exception and later blocks will not be examined.

The compiler will enforce listing the most derived exception types first.  In the example below,  FileNotFoundException derives (indirectly) from Exception.  A handler for Exception cannot precede a handler for FileNotFoundException because the Exception handler will catch exceptions of both types.  The code below results in a compiler error.

                try
                {
                    DoSomething();
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Exception");
                }
                catch (FileNotFoundException noFileExc)
                {
                    Console.WriteLine("FileNotFoundException");
                }

868-001

Advertisements