是否可以忽略使用try-with-resources语句关闭资源时抛出的异常?
例:
class MyResource implements AutoCloseable{
@Override
public void close() throws Exception {
throw new Exception("Could not close");
}
public void read() throws Exception{
}
}
//this method prints an exception "Could not close"
//I want to ignore it
public static void test(){
try(MyResource r = new MyResource()){
r.read();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
或者我应该继续关闭finally?
public static void test2(){
MyResource r = null;
try {
r.read();
}
finally{
if(r!=null){
try {
r.close(); …Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
class Bum implements AutoCloseable{
public void bu() throws Exception{
System.out.println("Bu");
throw new Exception();
}
@Override
public void close(){
System.out.println("Closed");
}
}
public class TestTryWith {
private static void tryWith(){
try (Bum bum=new Bum()){
bum.bu();
}catch (Exception ex){
System.out.println("Exception");
//ex.printStackTrace();
}
}
private static void tryCatchFinally(){
Bum bum=new Bum();
try{
bum.bu();
}catch (Exception ex){
System.out.println("Exception");
}finally{
bum.close();
}
}
public static void main(String[] args) {
tryCatchFinally();
System.out.println("------------");
tryWith();
}
}
Run Code Online (Sandbox Code Playgroud)
输出为:
Bu
Exception
Closed
------------
Bu
Closed
Exception
Run Code Online (Sandbox Code Playgroud)
我读过try-with-resources被编译器转换为try-catch-finally块。但是,您看到的顺序是不同的。当我们使用try-with-resources时,在catch子句之前调用close方法。为什么?