9

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

try{  
//code

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

最好的放置位置在哪里finally?或者我应该把它放在嵌套和外部try

4

3 回答 3

24

如果您希望块中的代码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
}
于 2012-12-12T08:37:51.590 回答
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 块之后。

于 2012-12-12T08:41:20.097 回答
1

来自文档

finally 块总是在 try 块退出时执行。这样可以确保即使发生意外异常也会执行 finally 块。但 finally 不仅仅对异常处理有用——它允许程序员避免清理代码意外地被 return、continue 或 break 绕过。将清理代码放在 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. 最终块
  2. finally 块是否总是运行?
于 2012-12-12T08:41:06.020 回答