Tuesday 28 September 2010

Checked and unchecked exceptions in Java

Over on Stephen Colebourne's blog, there's a discussion on whether checked exceptions in Java were a bad idea.

It seems to me that if you declare an exception as being a checked exception, you're effectively making three claims:

  1. You can't programmatically prevent this exception from occurring.
    Declaring checked exceptions requires you to put in code to recover from the exception.  It makes no allowance for code that actually won't ever cause the exception in the first place.  You can swear blind "No that can't throw a MalformedUrlException because I already know http://www.twitter.com is well formed", but the compiler will require you to catch a MalformedUrlException nonetheless.  (That trivial example could, for instance, be irritating if you've got a little throwaway app where you want to declare a URL as a static final constant.  The checked exception gets in the way even though it will never be thrown.)
  2. You're so likely to forget to handle this case, and it is likely enough and serious enough to occur, that I'm going to force you to decide how you're going to deal with it right now ...
  3. ... but it's not so terminal or abnormal that most applications shouldn't try to catch it
    (That's Error.)

Item 1 in that list makes me think checked exceptions should be rare.  Prevention is sometimes better than cure, but checked exceptions force you always to write a cure -- even if you've already prevented it.

But rare is not the same thing as non-existant.  Personally, I think File IO exceptions being checked is reasonable, for example.

No comments: