#865 – A catch Block Specifies the Type of Exception to Catch

In most cases, a catch block will specify the type of exception to intercept and catch.  Any exception occurring in the associated try block whose type matches the type indicated in the catch block will be caught.  Exceptions whose type is derived from the specified exception type will also be caught.

In the example below, we catch only exceptions of type FileNotFoundException, or of types that derive from this type. Other exception types will not be caught and will continue to bubble up the call stack.

            try
            {
                DoSomething();
                AskUserForFilename();
                DoSomethingElse();
            }
            catch (FileNotFoundException fnfExc)
            {
                Console.WriteLine(string.Format("Hey, we can't find file {0}!", fnfExc.FileName));
            }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #865 – A catch Block Specifies the Type of Exception to Catch

  1. Pingback: Dew Drop – June 13, 2013 (#1,567) | Alvin Ashcraft's Morning Dew

  2. Pingback: #889 – Catching Exceptions that Derive from a Common Base Type | 2,000 Things You Should Know About C#

Leave a comment