Quantcast
Viewing all articles
Browse latest Browse all 15

#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.


Filed under: Exceptions Tagged: C#, catch, Exceptions, try Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 15

Trending Articles