Putting try catch finally block inside another finally block

前端 未结 5 1101
孤独总比滥情好
孤独总比滥情好 2021-02-07 00:57
 try {
 } catch() {}
 finally {
     try {
     } catch() { }
     finally { }
 }

Is it good to have the code like above?

相关标签:
5条回答
  • 2021-02-07 01:22

    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.

    0 讨论(0)
  • 2021-02-07 01:24

    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;
      }
    }
    
    0 讨论(0)
  • 2021-02-07 01:26

    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.

    0 讨论(0)
  • 2021-02-07 01:34

    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

    0 讨论(0)
  • 2021-02-07 01:42

    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

    0 讨论(0)
提交回复
热议问题