java - 什么时候使用 try multi catch?

标签 java exception try-catch

我不明白什么时候使用 multi catch。我看到一些帖子说 multi catch 异常的编译时类型是多个异常类型中最接近的父类(super class)型。

假设存在异常类型 A、B 及其最接近的父类(super class)型 C。

选项 1

try{//whatever}
catch(A|B ex){//whatever}

选项 2

try{//whatever}
catch(C ex){//whatever}

选项 3

try{//whatever}
catch(A ex){//whatever}
catch(B ex){//whatever}

当抛出多个异常时,我们应该在哪些理想情况下使用上述选项?

最佳答案

根据 Oracle documentation ,新的多捕获 block 的显着点是:

catch (IOException|SQLException ex) {
   logger.log(ex);
   throw ex;
} 

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

如果可以以不同方式处理异常,那么我相信您应该单独捕获它们。如果多个异常的异常处理相同,那么您可以使用 multi-catch block 。

try{//whatever}
catch(A ex){//do something specific for A}
catch(B ex){//do something specific for B}

try{//whatever}
catch(C ex){
 //C is superclass of A and B and you are not concerned about the specific type 
 // will catch even other exceptions which are instanceof C
}

try{//whatever}
catch(A|B ex){//do the same thing for both A and B}

关于java - 什么时候使用 try multi catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17335510/

相关文章:

java - 共享异常实例是否安全

java - 使用 GNU 读取连续数据时在尝试中调用匹配器函数

尽管 try- except block ,Python 脚本仍以退出代码 255 退出

java - 如何克服 org.springframework.dao.RecoverableDataAccessException?

c# - 如何避免在 try-catch block 内定义 'Unassigned Local Variable'

java - 编写带有实例参数的Java类,检索参数并打印结果

java - 从 List<Date> 创建一个 List<List<Date>> ,其中包含随后放入列表中的所有日期

java - 两次 eclipse 警告的原因

java - HashMap问题,打印邻居

Android: Sqlite Exception 没有这样的表?