#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));
            }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: