Sunday, September 07, 2003


On Checked Exceptions.

Significant disagreement in the blogosphere -- what a surprise! I've read a number of entries disagreeing with my approach to checked exceptions. Let's look at a few of the objections:

1. An exception subclass doesn't tell you what's wrong. Last time I checked, every exception supports the getMessage() call. There's nothing stopping people from implementing that and ensuring that good, accurate messages are present in string form. In fact, it's pretty much a requirement that they be there. So if you have a subclass you're able to divert control based on being a subclass, but also able to simply deal with a more general case of having a string-based error message.

2. It's all just a goto. I don't think it is. Exceptions do a whole bunch of things that goto simply doesn't do. Yes, we could simulate them. No, we shouldn't do that. The whole point behind checked exceptions is to ensure that things are cleaned up correctly when something goes wrong.

The main point is this: It is very rare that we actually care what has gone wrong. We just know that something has. What we really care about are the categories of responses we can make to a given kind of error. I think there is a significant case to be made for throwing separate exception families for a given response category. For example -- if you are iterating through a loop that is performing remote calls and you encounter a remote communications error, you probably want to exit the loop. You're not going to be getting anywhere further, and more calls aren't necessary. You need to engage a certain logic pathway to deal with that. If your iteration call encounters some kind of localized, "I can't deal with this object" error, then you might want to skip over that specific object and move on to the next one.

There are various forms of error response, each divided by category. One size does NOT fit all. And in many cases, we want to ensure that the appropriate handling has take place. Checked exceptions are really the only static way to get at this problem. On projects of any significant size, static methods are the only way to succeed. Putting an app into production and then hoping you have all your RuntimeExceptions caught is a guaranteed way to fail.

I use RuntimeExceptions for one thing -- a problem that should NEVER happen in a production run. Sometimes we will choose to ignore the problem and move on, but it signifies a bug in the software.

Checked exceptions are for everything else -- a RARE event, something that the developer acknowledges COULD happen in a normal production run. These are preferably categorized (via subclassing or some other mechanism) by essential response characteristic.


3:28:08 AM