如何在尝试使用资源时调用方法

How to call a method in try with resources

我正在使用 try..finally 代码,但我想将 try 与资源一起使用,但我不确定如何在 try 与资源中调用方法,有人可以帮助我吗?

最终使用尝试

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

}

尝试使用资源

try(){
}
catch{}

但我不确定如何在不使用 finally 的情况下调用 reportAbc() 方法。

这是来自文档:

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.

正如 所说,您的资源在离开代码块和进入 catchfinally 块之间关闭。

问题的示例代码不完整,语法错误。这是一个完整的例子。

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

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

}

注意用于声明资源的括号对。这些对象必须实现 AutoCloseable。多个资源将按照它们在括号中列出的相反顺序关闭。