Documentation says
However, in this example, if the methods
readLine
andclose
both throw exceptions, then the methodreadFirstLineFromFileWithFinallyBlock
throws the exception thrown from thefinally
block; the exception thrown from thetry
block is suppressed. In contrast, in the examplereadFirstLineFromFile
, if exceptions are thrown from both thetry
block and thetry
-with-resources statement, then the methodreadFirstLineFromFile
throws the exception thrown from thetry
block; the exception thrown from thetry
-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 thetry
-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 ?
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();
}
}
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.