Putting try catch finally block inside another finally block

前端 未结 5 1099
孤独总比滥情好
孤独总比滥情好 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: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;
      }
    }
    

提交回复
热议问题