java - finally 在嵌套的 try/catch 中放在哪里?

标签 java exception coding-style try-catch

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

try{  
//code

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

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

最佳答案

如果您希望 finally block 中的代码无论在任何一个 block 中发生什么都运行,请将其放在外部 try 中。如果您只希望它在第一个 try block 中无论发生什么 都运行,请将其放在那里:

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
}

关于java - finally 在嵌套的 try/catch 中放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835749/

相关文章:

java - 发布集合中的 wsdl 模式名称冲突

java - 我可以使用 FileChooser (javafx) 将序列化对象保存在文件中吗?

java - 如何使用 Spring 调用自定义注释?

java - 处理多个流中的所有异常

c - 在具有一个输入和一个输出的函数中输出错误消息是一种不好的做法吗?

java - 如何在java中从Jersey模拟requestContext.getUriInfo().getPathParameters()

java - 无效输入请求的 REST 服务异常

exception - 流畅的 Cassandra : What does "Apache.Cassandra.UnavailableException" mean?

c++ - 转发声明或自给自足的标题?

c++ - 如何用 int * 修改 C++ 结构