Tony Tony - 16 days ago 10
Java Question

Two close methods in try-with-resources

I've got the following code:

try(Socket s1=new Socket(...); Socket s2=new Socket(...);)
{
some logic...
}


As I understood, Java closes
s2
first and then
s1
.
What will happen, if
s2.close()
throws exception? Will Java try to close
s1
after previous failure?

Answer

Quoting JLS Sec 14.20.3 (emphasis mine):

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.