Arpad Toth

Programming Addict

The problem with checked exceptions

April 08, 2016
When I first started to write Java code, I used to think that checked exceptions were really great. I still kind of like the idea, it’s just that the specific implementations can be problematic.

The versioning problem

Let’s say I create a method foo that throws exceptions E1 and E2. In version two of foo, I want to add a bunch of features, and now foo might throw exception E3. It is a breaking change for me to add E3 to the throws clause of that method, because existing caller of that method will almost certainly not handle that exception. In a language without checked exceptions this won’t be an issue because in a lot of cases, people don’t care. They’re not going to handle any of these exceptions because there is a bottom level exception handler around the message loop. The handler is just going to bring up a dialog or log the error and continue.

The meaningless code problem

The throws clause, at least the way it’s implemented in Java, doesn’t force you to handle the exceptions, but if you don’t handle them, it forces you to acknowledge precisely which exceptions might pass through. It requires you to either catch declared exceptions or put them in your own throws clause. To work around this requirement, people do ridiculous things. For example, they decorate every method with, “throws Exception.” That just completely defeats the feature, and you just made the programmer write more meaningless code.

The scalability problem

Let’s assume you start building a big system where you’re talking different subsystems. Each subsystem throws some exceptions. Now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. You end up having to declare, for example, 40 exceptions that you might throw. And once you aggregate that with another subsystem you’ve got 80 exceptions in your throws clause. In the large, checked exceptions become such an irritation that people completely avoid the feature. They say, “throws Exception,” everywhere; or they say, “try, catch catch catch curly curly…” They think, “Oh I’ll come back and deal with these empty catch clauses later,” and then of course they never do. In those situations, checked exceptions have actually degraded the quality of the system in the large.

Conclusions

I think the Java version (I really don’t know any other language that has checked exceptions) of checked exceptions do more harm than good and I usually avoid using them. In Java I try to use RuntimeException where possible. Apparently I am not the only one who thinks checked exceptions are not so great, for more details check this post from Misko Hevery.
I'm a Software Developer with 10+ years of experience, indie Android App Developer, Co-Founder at Interactions Lab, makers of AgroGo who loves playing guitar, hiking and ocasionally writing on this blog.