Putting try catch finally block inside another finally block

半世苍凉 提交于 2019-12-09 07:48:32

问题


 try {
 } catch() {}
 finally {
     try {
     } catch() { }
     finally { }
 }

Is it good to have the code like above?


回答1:


Yes, you can do this.

Actually, you are even required to do it when dealing with streams you want to close properly:

InputStream in = /* ... */;
try {
} catch (...) {
} finally {
    try {
        in.close();
    } catch (...) {
    } finally {
    }
}

I don't see any case in which this would be a bad practice




回答2:


For readability you can factor out the nested try-catch in to a separate method, like:

  try{
  }catch(){}
  finally{
    cleanup();
  }

And the second try-catch can be inside the cleanup method.

To support the above pattern in IO package, JAVA6 introduces a new class called Closeable that all streams implement, so that you can have a single cleanup method as follows:

public static boolean cleanup(Closeable stream)
{
try{
    stream.close();
    return true;
  }catch(){
    return false;
  }
}



回答3:


Looks ugly but sometimes it's the way to go. Depending on the code consider to extract a method with the second try-catch-finally block.




回答4:


It is best to avoid it when you can, but sometimes it may be necessary. If you tell us more about why you think you need this, we may be able to give better answers :-)

One reason to think about may be to commit a transaction in the finally block, when the commit operation itself may throw an exception.

It is important to note that exceptions thrown inside a finally block may easily shadow exceptions thrown earlier, within the try block, unless handled properly. Thus such nested try/catch blocks are sometimes the way to go. However, as others have noted, to improve readability, it is advisable to extract the insides of the finally block into a separate method.




回答5:


It's ugly, but there are cases where you can't avoid it, especially in resource clean up where you have dependent resources and the clean up of one resource can throw an exception.

A typical example is tidying up ResultSet, Statement and Connection objects in JDBC code. Closing the ResultSet can throw an exception, but we'd still like to continue and close the Statement and Connection



来源:https://stackoverflow.com/questions/6095664/putting-try-catch-finally-block-inside-another-finally-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!