Saturday, December 25, 2010

Exceptions in Java

Java has two types of exceptions: checked and unchecked. Unchecked exceptions are the traditional exceptions you see in languages like C++ and C#. Checked exceptions are essentially more explicit versions of unchecked exceptions. Checked exceptions require that the developer explicitly declare what exceptions a method could throw. The compiler will then enforce methods higher in the call stack to either catch the exception, or propagate it to a higher level.

Checked exceptions are a feature specific to Java. It was introduced into Java as an experiment, and the general consensus from developers is that the experiment failed. This is probably why no newer languages support them.

What's the problem with checked exceptions? They seem like a great idea in theory. They allow the code to be explicit with all error handling code, and make it impossible to forget to catch an exceptions. Unfortunately there are a lot more drawbacks with checked exceptions.

My main issue with them is that they clutter the code quite a bit. There is a lot of extra noise that goes into your code when you use checked exceptions. Not only does this make the code less readable, but it slows down development. For instance, you should not have to catch every single exception when you are writing test code or quick prototypes. A lot of the time, developers will just "swallow" the exceptions with empty catch blocks, because there is no intelligent way to recover. Does your tiny app really need to catch OutOfMemoryExceptions around every statement that might allocate memory? Even if you do catch it, how will you gracefully recover? The extra verbosity becomes noise that clutters the program's logic.

This argument reminds me of static typing vs. dynamic typing. If you choose static typing, you lose some flexibility, but gain some extra static analysis from your compiler. The same thing applies with checked exceptions, however the benefit they offer isn't worth the inflexibility.

What are your opinions on checked and unchecked exceptions in Java?

1 comment:

  1. It still sounds like a good idea to me.

    Though I guess everyone else thought so in theory too, so...