Amnesh Goel
Amnesh Goel

Reputation: 2655

How to catch exception thrown by close method in try-with-resource statement

I was reading about try-with-resource statement in Java which can be used to specify any number of resources.

try (Resource1 res1 = initialize_code; Resource1 res2 = initialize_code; ...) 
{
    statement;
}

Now when the try block exits (normally or abnormally throwing an exception) the close methods of all resource objects are invoked. But some close methods can throw exceptions. What will happen in that scenario if close itself throws exception?

Upvotes: 4

Views: 859

Answers (1)

akhil_mittal
akhil_mittal

Reputation: 24157

But some close methods can throw exceptions.

Yes they can and you are right. Also the resources are closed in reverse order of their initialization.

What will happen if close method itself throws exception?

As you mentioned some close methods can also throw exceptions. If that happens when try block is executed normally then the exception is thrown to caller.

But what when another exception had been thrown, causing close methods of the resources to be called, and one of the close method throws an exception (exception of lower importance actually)?

In this situation original exception gets rethrown and the exceptions caused by close method are also caught and attached as supressed exception. This is actually one of the advantge using try-with-resource becuase implementing such mechanism would be tedious to implement by hand.

try {
 ///statements.
} catch (IOException e) { 
   Throwable[] supressedExceptions = ex.getSupressed();
}

Upvotes: 4

Related Questions