捕获多个异常时的特定和相同操作

Mik*_*cer 9 java exception-handling try-catch java-7

我想以不同的方式处理两种不同类型的异常,然后对两种异常类型进行相同的操作.如何用Java做到这一点?

以下代码显示了我想要做的事情,但它不正确,因为一个例外无法捕获两次.

这个的正确语法是什么?

try {
    // do something...
} 
catch (ExceptionA e) {
    // actions for ExceptionA
}
catch (ExceptionB e) {
    // actions for ExceptionB
}
catch (ExceptionA | ExceptionB e) {
    // actions for ExceptionA & ExceptionB
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*nic 6

使用catch (ExceptionA | ExceptionB e)构造.在catch块中,首先分别instanceof检查e和处理异常类型.在此之后,对这两种类型进行常规处理.这样你就可以在一个catch块中完成所有事情:

try {
    // do something...
} catch (ExceptionA | ExceptionB e) {
    if (e instanceof ExceptionA) {
        // handling for ExceptionA
    } else {
        // handling for ExceptionB
    }
    // common handling for both exception types
}
Run Code Online (Sandbox Code Playgroud)