finally
如何在嵌套try/catch
中工作?
例如。 for:
try{
//code
}
catch(SomeException e){
//code
try{
//code
}
catch(OtherException e){
//code
}
}
catch(SomeOtherException e){
//code
}
放置finally
的最佳位置在哪里?或者我应该将它放在嵌套和外部try
中吗?
答案 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
}
有关详细信息,请查看以下链接。