Try without catch in the JDK

06 Jul 2006

The practice of using a try statement with a finally statement but without a catch statement came up on the PMD forums recently. This construct is used in a couple places in the JDK:

  • PlainSocketImpl uses this in several spots, mostly inside small methods (like close()) that declare IOException. For example, if there's an IOException while a socket is in the accept state, a finally block will release the FileDescriptor and then the IOException will move up the stack to the next caller.
  • BeanContextSupport uses this idiom to support serialization - if there's an exception while serializing, a state variable (aptly named 'serializing') will be set to false by the finally block and the exception will propagate to the caller.
  • Toolkit has a try without catch in 'getDefaultToolkit'. At the beginning of that method the JIT compiler is disabled and a finally block at the end of the method ensures it's properly reenabled.

These examples are all from JDK 1.4; I'm not sure how prevalent this is in newer JDKs. Here's the PMD XPath rule to find this:


For much more along these lines, check out the PMD book!