Home > Blockchain >  How to call a method in try with resources
How to call a method in try with resources

Time:10-01

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.

CodePudding user response:

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: A try -with-,resources declared have been closed.

CodePudding user response:

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.

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.

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

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

}
  • Related