Damn you empty catch block

In the code I help maintain in my day job, I see a lot of the following code:

try
{
/* code */
}
catch(Exception)
{
}

I see it in several different languages almost daily. It really frustrates me that my colleagues and predecessors did this. I stamp it out ruthlessly.

Here is a great post on why empty catch blocks are bad. Here is a great question and series of answers on StackOverflow about best practices for exception handling.

  1. At a previous workplace of mine I found that a wrapper, which had only a “try” and a “finally” (it was designed to clean up after exceptions), was eating exceptions. I investigated to find that between the lovingly-crafted “try” and “finally” blocks, someone had inserted the following:

    catch( Exception e ) {
      int i = 0;
    }

    An svn blame later and I was over at the culprits desk. Apparently the code was there so that he “could debug it”; he just needed a line of code where an exception would be caught that he could put a breakpoint on.

  2. COM interop makes you do it. There are some horrendous COM APIs out there and those that dont return S_OK throw an excaption in .net, which is horrible. I recently had to use the Task Scheduler COM API and it had an unqueryable dictionary – the only way to test was to Get and catch the exception which simply was the HRESULT saying key not found.

    Sometimes an empty catch block is better than a shitty COM API bombing out your app when the HRSEULT is actually perfectly valid……

  3. COM Interop is a dirty, and necessary evil, and I’ve had to do my fair share of it. Exception handling can be a pain, admittedly. A lot of the time though, I’d still rather add a log or trace message rather than just leave it empty.

    This blog post was more aimed toward the more general case of someone swallowing an exception either because they were lazy or didn’t see the benefit of logging the error or some such.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>