最后放在嵌套的try / catch中的位置?

时间:2012-12-12 08:36:09

标签: java exception coding-style try-catch

finally如何在嵌套try/catch中工作? 例如。 for:

try{  
//code

}  
catch(SomeException e){  
   //code  
   try{  
      //code  
   }  
   catch(OtherException e){  
     //code  
   }  
}  
catch(SomeOtherException e){    
  //code  
} 

放置finally的最佳位置在哪里?或者我应该将它放在嵌套和外部try中吗?

3 个答案:

答案 0 :(得分:22)

如果您希望finally块中的代码无论在哪个块中发生什么都要运行,请将其放在外部try上。如果你只想让它在第一个try块中的 内发生,那就把它放在那里:

try{  // try/catch #1
  //code block #1

}  
catch(SomeException e){  

   //code block #2

   try{  // try/catch #2
      //code block #3
   }  
   catch(OtherException e){  
     //code block #4
   }  
   finally {
     // This code runs no matter what happens with try/catch #2 (so
     // after code block #3 and/or #4, depending on whether there's
     // an exception). It does NOT run after code block #1 if that
     // block doesn't throw, does NOT run after code block #2 if
     // that block DOES throw), and does not run if code block #1
     // throws SomeOtherException (code block #5).
   }
}  
catch(SomeOtherException e){    
  //code block #5
} 
finally {
  // This code runs no matter what happens with EITHER
  // try/catch #1 or try/catch #2, no matter what happens
  // with any of the code blocks above, 1-5
}

更简要:

try {
   // covered by "outer" finally
}
catch (Exception1 ex) {
   // covered by "outer" finally

   try {
     // Covered by both "inner" and "outer" finallys
   }
   catch (Exception2 ex) {
     // Covered by both "inner" and "outer" finallys
   }
   catch (Exception3 ex) {
     // Covered by both "inner" and "outer" finallys
   }
   finally { // "inner" finally
   }
}
catch (Exception4 ex) {
   // covered by "outer" finally
}
finally { // "outer" finally
}

答案 1 :(得分:3)

这取决于您希望finally块中的代码执行的位置。

try{  //Try ROOT
//code

}  
catch(SomeException e){  //Catch ROOT ONE
   //code  
   try{  //Try NEST
      //code  
   }  
   catch(OtherException e){  //Catch NEST
     //code  
   }
   finally{
     //This will execute after Try NEST and Catch NEST
   }
}  
catch(SomeOtherException e){    //Catch ROOT TWO
  //code  
}
finally{
  //This will execute after try ROOT and Catch ROOT ONE and Catch ROOT TWO
}

没有最好的地方取决于您想要的功能。但是如果你想让finally块只在所有try catch块之后运行,那么你应该把它放在最后的根catch块之后。

答案 2 :(得分:1)

来自Doc

  

当try块退出时,finally块始终执行。这确保即使发生意外异常也会执行finally块。但最终不仅仅是异常处理有用 - 它允许程序员避免因返回,继续或中断而意外绕过清理代码。将清理代码放在finally块中总是一种很好的做法,即使没有预期的例外情况也是如此。

最好将你的终点放在需要的地方。

try{  
  //code

 }    
 catch(SomeException e){  // 1
     try{  //Try Block 
       //code  
      }  
     catch(OtherException e){  //2
       //code  
      }
     finally{
       //This will execute after Try Block and Catch Block 
      }
 }  
catch(SomeOtherException e){  //3
  //code  
 }
finally{
   //This will execute after 1 and 2 and 3
 }

有关详细信息,请查看以下链接。

  1. The finally Block
  2. Does a finally block always run?