javatry-with-resources

Exceptions from both try block and try-with-resources


Documentation says

However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

I don't understand the bold part

... if exceptions are thrown from both the try block and the try-with-resources statement ...

How can an exception be thrown from both the try-with-resources statement and the try block ? If the exception is thrown from the try-with-resources statement, it means that resource initialization failed. In this case, try block is never executed. Thus the previous statement can't happen.

I must have misunderstood this documentation and how try-with-resources works. Can you provide example where the bold statement actually happens ?


Mentioned methods
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

Solution

  • How can an exception be thrown from both the try-with-resources statement and the try block ? If the exception is thrown from the try-with-resources statement, it means that resource initialization failed.

    The try-with-resources statement not only initializes but also closes the resource, and closing may throw an exception.

    This sentence comes right after a description of a similar situation when using try-finally, and compares it with try-with-resources.