我有以下代码:
try {
/* etc. 1 */
} catch (SomeException e) {
/* etc. 2 */
} catch (SomeException e) {
/* etc. 3 */
} finally {
/*
* do something which depends on whether any exception was caught,
* but should only happen if any exception was caught.
*/
/*
* do something which depends on whether an exception was caught and
* which one it was, but it's essentially the same code for when no
* exception was caught.
*/
}
所以,我想保留我捕获的异常。除了在每个 catch 块中分配一个变量之外,还有什么方法可以做到这一点?
编辑:为了澄清,请不要发布建议我使用 try 块之外的变量的答案。我知道我能做到,这个问题的重点是找到一个替代方案。
现在,我真正想要的是更灵活的catch 块,以便多个catch 块可以捕获相同的异常,例如catch(Exception e)
即使它已经被捕获也会捕获所有内容,catch(Exception e) except(NullPointerException, IllegalArgumentException)
会跳过异常。并且一个 catch 块可以catchingcontinue;
跳过同一个 try 块的所有其他 catch 块,catchingbreak;
甚至跳过 finally。