Can someone please explain to me what is happening here and in which order?. The output doesn't make any sense to me.
The output is T 1 IOE F.
The code is:
import java.io.Closeable;
import java.io.IOException;
public class TestRes {
public static void main(String[] args) {
try (
MyResource11 r1 = new MyResource11();
MyResource21 r2 = new MyResource21();
)
{
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
}
class MyResource11 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource21 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
try-with-resources closes the resources in the opposite order to the order they were declared in. So that code:
T
r2
r1
, which outputs 1
r2
) and outputs IOE
F
It's worth reading through the try-with-resources part of the JLS, which includes code examples of an unravelled try-with-resources statement (e.g., the equivalent code with just try
/catch
/finally
). From that section:
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.