The try-with-resources clause adds an implicit close() call for any resources
declared. This close() call may throw checked exceptions that aren't handled or
declared by the surrounding code. This will result in a compile-time error.
If this error occurs, the caret points to the incorrect position in the source.
Also, the error message could be improved.
Consider the following program:
========================================
package com.example.twr;
import java.io.*;
import java.sql.*;
class MyException extends Exception { }
class MyCloseable implements AutoCloseable {
public void close() throws MyException { }
}
public class ExceptionOnClose {
ResultSet getResultSet() { return null; }
void p(Statement stmt) {
try (MyCloseable x = new MyCloseable();
ResultSet rs = getResultSet();
FileInputStream fis2 = new FileInputStream("bar")) {
} catch (IOException ioe) {
}
}
}
========================================
When compiled, the error is as follows:
ExceptionOnClose.java:25: unreported exception MyException; must be caught or declared to be thrown
FileInputStream fis2 = new FileInputStream("bar")) {
^
1 error
The caret points to the open brace of the try-block. This is clearly the wrong
location, since it's not where the implicit close() is, and the close() is on
a resource that in this case is on a different line.
The caret could point to the close brace of the try-block, but this is even farther
from the declaration of the resource being closed.
Since the exceptions thrown by the close() call are dependent upon the type
of the resource being closed, perhaps it makes most sense for the caret to
point to the declaration of that resource.
The error message would also be improved by adding a mention that this exception
is generated by the implicit close() of a resource. Perhaps something like:
"exception MyException from implicit close() of resource must be caught or declared to be thrown"