August 19, 2005

Bruce Eckel: Does Java need Checked Exceptions? Naturally a religious issue, but worth considering. What seems like a good idea in theory can be a bad idea in practice.

comments...

One of the things I vividly remember missing when I started doing more C# than Java was the compile-time exception checking. I felt naked without it. It was very helpful to know what possible exceptions could be thrown at a given place in the code, so that you could effectively do local mitigation for non-fatal exception conditions.

With C# you have to do a more trial and error approach to figure this out.

Since C# Reflection is so easy to use, alot of C# code I see now does late binding assembly loading, which effectively would negate any benefit from compile time exception handling. The popularity of plugin architectures and component modules warrant a different attitude for exception handling.

My first inclination is that checked exceptions are an important part of an API definition: "This method returns a Foobar on success, or throws a BazException if the Foobar is unavailable." They're like old-fashioned return codes, except they don't get in the way of the typed value returned from a successful call, and have their own type checking with catch/throws enforcement.

Like old-fashioned return codes, they can be cumbersome to use, since they demand an appropriate reaction from every piece of code in the call chain. I believe Eckel's point is that the developer overhead is almost never worth it, and in large complicated systems, the exceptions are often mismanaged just to cheat the overhead of coding appropriate reactions.

I often feel like I want a complete list of all exceptions, checked and unchecked, that a method can throw. I don't want to have to wait until a runtime error occurs to find out that a method is capable of producing special cases I need to handle. To this end, it's a documentation (and developer education) issue, and checked exceptions aren't much more than compiler-enforced documentation conventions. That isn't necessarily a bad thing.

But if we're talking developer education, then perhaps we just need a culture of better coding habits that put in the effort to handle checked exceptions appropriately. Eckel is saying that experience has shown that such habits don't come naturally, and that makes the language feature difficult to use.