相关疑难解决方法(0)

尝试捕获 - 最后再尝试捕获

我经常遇到这样的情况: -

try{ 
     ...
     stmts
     ...
} 
catch(Exception ex) {
     ... 
     stmts
     ... 
} finally {
     connection.close // throws an exception
}
Run Code Online (Sandbox Code Playgroud)

最后还需要一个try-catch块.

克服这个问题的最佳做法是什么?

java exception-handling try-catch-finally

31
推荐指数
3
解决办法
2万
查看次数

使用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万
查看次数