Don't hide stuff in catch alls

At times it can be tempting to hide minor problems with a catch all. You know, like pesky NPE's, if they don't really cause you any problems if they happen why shouldn't you just ignore them?

It comes down to maintenance, the next developer that reads your code will think that the catches are there for a reason. A reason other than what you had in mind.

Consider the following:

 try {
    cell = new PdfPCell(new Phrase(new Chunk("text:", uheaderFontB)));
    cell.setBorder(0);
    tbl.addCell(cell);

    cell = new PdfPCell(new Phrase(new Chunk(obj.getId(), uheaderFontB)));
    cell.setBorder(0);
    cell.setColspan(4);
    tbl.addCell(cell);

    String earlierDate = formatDate(obj.getPublEarlierDate());

    cell = new PdfPCell(new Phrase(new Chunk("Bad:", uheaderFont)));
    cell.setBorder(0);
    tbl.addCell(cell);

    cell = new PdfPCell(new Phrase(new Chunk(earlierDate, uheaderFont)));
    cell.setBorder(0);
    cell.setColspan(4);
    tbl.addCell(cell);

    cell = new PdfPCell(new Phrase(new Chunk(obj.getText(), uheaderFont)));
    cell.setBorder(0);
    cell.setColspan(5);
    tbl.addCell(cell);

} catch (Exception e) {
    logger.error(e.getMessage());
    e.printStackTrace();
}   

This is a piece of real code that I'm working with, now what the hell is that Exception catching? It turns out this code doesn't throw any checked exceptions. My problem now is that I don't know why it's there. Is it because something throws an NPE? Is just left over code from something earlier that did throw something? I don't know, and now I'm to afraid to change this.

To avoid this do the following:

  • Keep your blocks tight
  • Be as explicit as possible with what you're catching
  • Don't swallow exceptions, i.e. just catch them and do nothing
  • If everything else fails, write a comment because your code isn't clear