相关疑难解决方法(0)

使用try-with-resources静静地关闭资源

是否可以忽略使用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)

java exception java-7 try-with-resources

27
推荐指数
3
解决办法
1万
查看次数

Java:try-with-resources vs try-catch-finally关于自动关闭的顺序

请考虑以下代码:

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方法。为什么?

java

1
推荐指数
1
解决办法
604
查看次数

标签 统计

java ×2

exception ×1

java-7 ×1

try-with-resources ×1