#866 – A catch Block Without Arguments Catches All Exceptions

You typically include an argument in a catch block that indicates the type of exception to catch.

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

You can also omit the arguments on the catch block entirely.  In this case, the catch block will catch all exceptions, regardless of their type.  Because you don’t declare an exception variable, however, you won’t have access to information about the exception.

            try
            {
                DoSomething();
            }
            catch
            {
                Console.WriteLine("No idea of what happened, but it must be something bad");
            }

Although possible, not specifying the type of exception to catch is not recommended.  Even exceptions originating from outside of CLS-compliant code will be wrapped in an exception whose type derives from Exception.  So you should always specify an exception variable in the catch clause.

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.

One Response to #866 – A catch Block Without Arguments Catches All Exceptions

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

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: