A Funny Java Flavoured Look at the World

Wednesday, May 31, 2006

Avoid empty catch blocks

When I was writing code under a very harsh deadline and there was smoke coming off the keyboard, I had left a few exceptions just being caught but without doing anything in them.

This is a really bad state of affairs and it's certainly not something I am proud of. I have been going back through today and deciding what I should do in some of these errors.

In most cases I am just logging out the error message with some information (like class name, method name and additional information). This might not seem that good but it's a whole lot better than having nothing in the catch block and at least you can get the customer to turn on the logger and read out the message to you.

I recently have been the beneficiary of this, I had a problem whilst installing the software at a customers site and turned on the login and although I didn't have a clue what was causing the problem, at least we knew where to look because we logged out the error message with a e.getMessage with the class name and method name in front of it.

Whilst feeling in the exception blocks, I thought how lucky I was that the code (thanks to some unit tests) worked but if it hadn't then I would have had a clue because there would have been no error messages in the log files to look at.

I have vowed not to let this sloppy coding practice continue, it would have only taken me a few minutes when writing the code. It can be easy to do this no code in the catch blocks because they are auto generated by eclipse but don't fall into the trap.

I think I am going to try and get eclipse to fill in the necessary code for me, so I won't forget, now that would be nice.

3 Comments:

  • And don't forget to get the PMD Eclipse plugin to catch such things in the future!

    By Blogger Tom Copeland, at Wed May 31, 01:37:00 pm 2006  

  • And just think, if it weren't for checked exceptions, you probably wouldn't have had this problem. (Lovely feature that encourages bugs in code, eh?)

    By Anonymous Anonymous, at Wed May 31, 04:42:00 pm 2006  

  • I think I am going to try and get eclipse to fill in the necessary code for me, so I won't forget, now that would be nice.

    And not that hard either, unless maybe you can't generalise enough because your logging method changes between (or within?) projects. At the very least you can add

    e.PrintStackTrace();

    Before the TODO in the standard block so something should happen when an exception is thrown.

    By Anonymous Anonymous, at Fri Jun 02, 09:09:00 am 2006  

Post a Comment

<< Home