VISHAL SAXENA VISHAL SAXENA - 3 months ago 12
Java Question

try with Resources

I have come across one doubt in "Try with Resources" topic .

Program code :

public class Suppressed_Exception_Eg03 {
public static void main(String[] args) {

try(Wolf obj=new Wolf(); Deer obj1=new Deer();){
//Both close statements are executed .
//Therefore , we see two closing stmts
}

catch(Exception e)
{
System.out.println(e.getMessage());

}

}

static class Wolf implements AutoCloseable
{

@Override
public void close() throws Exception {
System.out.println("Closing Wolf !");
throw new RuntimeException("In Wolf !");
}

}


static class Deer implements AutoCloseable
{

@Override
public void close() throws Exception {
System.out.println("Closing Deer !");
throw new RuntimeException("In Deer !");

}
}
}


Output :

Closing Deer !
Closing Wolf !
In Deer !


Doubt : We all are aware that close method for Deer class will be closed first and following will be of Wolf class . Accordingly , the exception thrown by Wolf class should suppress the exception thrown by Deer class .
So , we should be catching Wolf class' exception in catch block . But here we can see in the output , Deer class' exception is caught and printed . Can some one explain why is that ?

Answer

The spec says:

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.

The first exception in your code (Deer) is not suppressed because there was no previous exceptions being thrown. Then, the next resource is closed (Wolf), but this time the exception from Wolf is suppressed.