{ by david linsin }

January 09, 2008

Wonderful Checked Exceptions

Effective Java says that checked Exceptions are a "wonderful feature of the Java language". A lot of people disagree. Stephen Colebourne, e.g. calls Exceptions an "experiment" and Joshua Gertzen goes a far as calling them a drudgery. I'm not too sure whether to like checked Exceptions or not, but most of the Exception classes I design are unchecked. Since I'm not developing an API of a library or framework, rather code that only my team has to deal with, I don't see any reason for implementing any checked Exceptions.
Use Checked Exceptions for recoverable conditions and Runtime Exceptions for programming errors
This guideline from Effective Java doesn't hold true for my code. Since there is no "real" API we implement, there are no "real" programming errors. I believe that most of the time when an Exception is raised, you can't recover from it anyways. So instead of forcing the caller to handle an Exception, I use runtime Exceptions and let him decide what to do. I don't want my code to be littered with unnecessary try/catch/finally blocks, cause that's the case if you have to deal with checked Exceptions (see the example below). Nevertheless, I believe it's important to document the thrown Exception, so that a caller is aware of, that an Exception could be thrown under certain circumstances. A couple of month ago, I heard about an idea of changing the Java language to allow catching multiple Exceptions. I'm quite excited about this change, since it would make code that looks like the following obsolete: Statement stmt = null; try { // do stuff that uses Statement instance } catch (SQLException e) { // handle state log.error("Bad database", e); } catch (NullPointerException e) { // handle state log.error("Bad parameter", e); } catch (Exception e) { // handle state log.error("Bad luck", e); } finally { try { stmt.close(); } catch (Exception ex) {} } There were a number of discussions on the Java Posse Google Group back than, which proposed different ideas of how the implementation could look like. In the mean time Neal Gafter implemented a prototype of his Closures proposal, which supports catching multiple Exceptions in one clause. I believe the example above could look like this instead: Statement stmt = null; try { // do stuff that uses Statement instance } catch (SQLException | NullPointerException | Exception e) { // handle state log.error(e); } finally { try { stmt.close(); } catch (Exception ex) {} } I think this would be a real improvement and something that a lot of developers out there would like to see in Java 7.

0 comments:


com_channels

  • mail(dlinsin@gmail.com)
  • jabber(dlinsin@gmail.com)
  • skype(dlinsin)

recent_postings

loading...