How to call a method in try with resources

618 Views Asked by At

I was using try..finally code but I want to use try with resource but I am not sure how to call a method in try with resource can anyone help me with that?

using try finally

try{
}
catch{}
finally{
//closed a resources 
//called a methods 
reportAbc();

}

using Try with resource

try(){
}
catch{}

but I am not sure how should I call reportAbc() method without using finally.

2

There are 2 best solutions below

0
MaxG On BEST ANSWER

This is from the documentation:

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#:~:text=Note%3A%20A%20try%20%2Dwith%2D,resources%20declared%20have%20been%20closed.

0
Basil Bourque On

As the correct Answer by MaxG said, your resources are closed in between leaving the code block and entering either catch or finally block.

The Question’s example code is incomplete with faulty syntax. Here is a full example.

try
(
    SomeResource someResource = … ;
)
{
    someResource.reportAbc() ;
    …

}
catch
{
    // someResource will have been closed by this point.
    …
}
finally
{
    // someResource will have been closed by this point.
    …

}

Notice the pair of parentheses for declaring resources. Those objects must implement AutoCloseable. Multiple resources will be closed in the reverse order in which they were listed in the parentheses.