Things I hate about Java – Exception handling

It’s not really something I hate about Java, more about books about Java and people who program in Java.  Every book and introduction to Java covers how to use checked exceptions, and the IDE tools all auto generate catch blocks that look like this:

try {
  // some code
} catch (IOException e) {


I have noticed that new Java programmers typically just write their methods to throw Exception so that they don’t have to deal with these checked exceptions, and then someone tells them to do this instead, and then I have to beat it out of them later when they work with me.

Logging an exception is not the same as handling an exception!

I would rather have methods just throw an exception instead of handling it badly.  So here are my rules for exception handling:

1) Don’t catch exceptions, just let them escape your method.

2) If you are implementing an interface and you can’t throw the exception that you need to, or if your method would need to throw 3 or more different checked exceptions, it is ok to wrap an exception in some other exception type, but you must include the original exception as the cause.

try {
  // some code
} catch (SpecificException e) {
  throw new GenericException(e);

 3) When rethrowing an exception don’t log it.  Let the receiver log it if they want.  They might have a perfectly good way to recover from that exception.  Can you imaging how annoying it would be if threw a FileNotFoundException and also logged it?  

4) If you are implementing the top level Runnable of a thread or an executor task, you must catch and handle all exceptions.  This is the one place where logging the exception might be the right answer. If you let it escape you will terminate your thread, or in a ScheduledTaskExecutor, you will stop the future tasks from running if you let an exception escape.

One thought on “Things I hate about Java – Exception handling”

  1. It seems like it might be fair to blame Java for this.

    I guess maybe people that think static typing is really wonderful probably like checked exceptions, but I don’t really see the point.

Comments are closed.