Arnt Gulbrandsen
About meAbout this blog
2011-07-28

catch( Exception e ) { throw new Exception( e ); }

Some Java book I read long ago, I think it was Thinking in Java, explains that one of the benefits of Java exceptions is that you can shift error handling away from the normal path, leaving the implementation of the common case clearer and better.

Fine. There's just one catch: You have to catch the exceptions and handle the error somewhere. Catching and rethrowing turns that plan into throw the error up in the air and hope it never comes down again.

I just now grepped through some code that deals with money changing hands and classified the catches. The first fifty (I lost heart and stopped long before the end): 46 rethrow the exception, a few also log something. 3 ignore the error, in one case correctly, not sure about the other two. And in one case, the program intentionally aborts (during startup).

4-8% of catches handle the error, 92-96% merely rethrow. And this isn't even particularly bad code. Better than the average for Java.

If this is what java's exception support leads to, there must be something terribly bad about the design.

Update: After more thought, I think the problem is that java, by default, allows exceptions to percolate up, up and out of main().

Wanting to handle errors elsewhere is fine. Wanting to handle errors not-here is not-fine. There's a subtle difference, and java gets it wrong. In java, you have to think and type in order to handle error elsewhere, but not handling errors at all requires typing merely .

If main() would never throw anything other than RuntimeException, and other exceptions couldn't be rethrown as RuntimeException, then the design would be more or less right. Everything would still be possible that's possible now, but typing wouldn't do the wrong thing.