Why is try-with-resources catch block selectively

2019-03-14 20:11发布

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.

4条回答
孤傲高冷的网名
2楼-- · 2019-03-14 20:43

Not every Java class (!) throws an exception. Sometimes you just want to use a try-with-resources to use the auto-close feature, and nothing else.

BufferedReader br = new BufferedReader(new FileReader(path));
try {
    return br.readLine();
} finally {
    if (br != null) br.close();
}

This the catch is optional because readLine() doesn't throw a (checked) exception.

Yes, close() could throw an exception, but the try-with-resources handles that too.

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
} 

So this try-with-resources doesn't need a catch.

查看更多
Evening l夕情丶
3楼-- · 2019-03-14 20:56

You could check the JLS but there is actually a relatively easy reasoning why this is the only correct way the language should behave.

The main rule of checked exceptions is that any checked exception declared by a method must be handled, either by catching it or letting the calling method throw it.

The try-with-resources always (implicitly) calls the close method.

So if the specific close method of the AutoClosable you use (determined by the type declared in try) declares to throw a checked exception such as a SQLException you do need to handle this checked exception somewhere, otherwise it would be possible to violate the rule!

If the close method does not declare that it throws a checked exception, the rule is not violated and you do not need to handle a checked exception for implicitly calling the close method. It is actually a compilation failure if you do try to catch a checked exception that is never declared to be thrown.

查看更多
一纸荒年 Trace。
4楼-- · 2019-03-14 20:57

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.

查看更多
老娘就宠你
5楼-- · 2019-03-14 21:05

You could just be throwing the exception up (or catching it in another try-catch block):

private static void test() throws IOException {
    try(InputStream is = new FileInputStream("test.txt")) {
        while(is.read() > -1) {
        }
    } finally {
        // Will get executed, even if exception occurs
        System.out.println("Finished");
    }
}
查看更多
登录 后发表回答