Why is try-with-resources catch block selectively optional?

Mer picture Mer · Aug 26, 2014 · Viewed 21.2k times · Source

I read that the catch block in try-with-resources is optional. I've tried creating a Connection object in a try-with-resources block, with no subsequent catch block, only to get compiler error from eclipse: "Unhandled exception type SQLException thrown by automatic close() invocation."

Since every resource that can be used in try-with-resources implements AutoCloseable, and so potentially throws an exception upon invocation of the close() method, I don't understand how the catch clause is optional, given that it's not allowing me to skip catching the exception from close().

Is there some special requirement that the specific implementation of AutoCloseable not directly declare any exception thrown in its close() method? (e.g. override AutoCloseable's close() throws Exception with a close() which does not throw any Exception)?

..or is this possibly just an eclipse issue?

Edit: Here's the simplest code fragment that still triggers the problem:

try (Connection con = dataSource.getConnection()) {
  /*...*/

}

Thoughts on whether or not this is related to the use of a JNDI DataSource?

Thanks in advance.

Answer

jdphenix picture jdphenix · Aug 26, 2014

It is optional if close() is not able to throw a checked exception. However, if close() can, then a checked exception would need to handled in a normal fashion, either with a catch block, or by throwing from the method that try-with-resources block is in.

More details are in JLS 14.2.3

14.20.3.2. Extended try-with-resources

A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

The meaning of an extended try-with-resources statement:

try ResourceSpecification
    Block
[Catches]
[Finally]

is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

try {
    try ResourceSpecification
       Block
}
[Catches]
[Finally]

The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

Thoughts on whether or not this is related to the use of a JNDI DataSource?

Yes, it is.

In the example try-with-resourses block you've provided, it is necessary to catch the exception and handle, or throw from the method the block is in, because SQLException is a checked exception.