Is it really that bad to catch a general exception?

Obviously this is one of those questions where the only real answer is “it depends.”

The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.

The reason for this is that e.g. you don’t want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like “OutOfMemoryException” which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits… well, it’s probably safe to catch just about any exception here.

The most important rule about catching all exceptions is that you should never just swallow all exceptions silently… e.g. something like this in Java:

try { 
    something(); 
} catch (Exception ex) {}

or this in Python:

try:
    something()
except:
    pass

Because these can be some of the hardest issues to track down.

A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.

Leave a Comment