15

This is not 'How To Catch All Exceptions' but rather 'Should You Catch All Exceptions'? In C# .NET I've noticed a tremendous amount of exceptions. Is it advisable to plan on catching every exception?

For example the DirectoryInfo() constructor throws 4 exceptions. Should I plan on catching these or only catch the ones that I can handle? Maybe let the others bubble up to Main() where I have a catch-all that then tells the user there is an uncaught exception. It just seems with all these possible exceptions your code could become more exception-handling than actual code.

6

4 Answers 4

19

Only catch the ones that make sense to handle for the level of abstraction at which you are writing the code. Most exceptions will only be caught at a much higher level than where they are thrown.

So yes, you are correct. :)

1
  • 3
    This. Only handle exceptions that you can, well, handle.
    – hometoast
    Jun 25, 2012 at 14:33
2

You should catch exceptions that you are expecting - and fail gracefully on exceptions that you aren't expecting (by catching them in a general exception handler).

In your example - creating DirectoryInfo() can throw multiple exceptions - but there is no reason you can't just

try 
{ 
   var di = new DirectoryInfo(somePath);
}
catch(Exception ex)  
{
   // Messagebox/alert the user etc, gracefully exit/cancel/throw if needed
}

It may be that you want to catch the security exception and provide some other code, well do it, but keep your 'general case' handler

try 
{ 
   var di = new DirectoryInfo(somePath);
}
catch(SecurityException ex) 
{
   // Carry on but use a default path or something etc
}
catch(Exception ex)  
{
   // Messagebox/alert the user etc, gracefully exit/cancel
}
0

Generally, you should only catch exceptions that you know how to handle. The purpose of exceptions bubbling up is to allow other parts of the code catch them if they can handle them, so catching all exceptions at one level is probably not going to get you a desired result.

At the top level, you may want to have a catch-all to give the user a friendly error message, and that would signal that your program is mis-handling something, and you may need to figure out how to handle it properly.

There are some cases (such as an OutOfMemoryException), that there really is no way to gracefully handle (other than exit), and you should definitely let those bubble up at least as far as the UI for a graceful exit.

0

Just catch those you can and want to handle.
The logic is pretty simple, what will you do with the rest of the "throw"s?
unless there is something (logic \ logging \ error messaging) you want to do and you just going to re-throw then you have no reason to catch.

Not the answer you're looking for? Browse other questions tagged or ask your own question.