Reputation: 101
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 ?
Upvotes: 5
Views: 342
Reputation: 3519
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.
Upvotes: 6