1

我有以下代码:

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。

4

4 回答 4

2

尝试这个:

try {
    // your code throwing exceptions
} catch (Exception e) { // This catch any generic Exception
    // do whatever you want to do with generic exception
    ...
    if (e instanceof SomeException) {
        ...
    } else if (e instanceof OtherException) {
        ...
    }
}

使用 java 7 你甚至可以这样做:

try {
    // your code throwing exceptions
} catch (SomeException|OtherException e) { // This catch both SomeException and OtherException
    // do whatever you want to do with generic exception
    ...
    if (e instanceof SomeException) {
        ...
    } else if (e instanceof OtherException) {
        ...
    }
}
于 2013-03-20T13:25:23.853 回答
1

您需要将其分配给块variable外部并在try-catch块上使用它finally

Exception caughtException = null;

try {
    /* etc. 1 */
} catch (SomeException e) {
    caughtException= e;
} catch (SomeOtherException e) {
    caughtException= e;
} finally {
    if (caughtException != null) {
        /* 
         * do something which depends on whether any exception was caught,
         * but should only happen if any exception was caught.
         */
    }
}

看起来你想做一些审计。为什么不使用一些注释AOP来处理行为,当然还有一个很好的异常处理来捕获之前或之后的那些异常。

于 2013-03-20T13:21:50.950 回答
1

将变量保留在 catch 块范围之外,并在 catch 块中分配它。

购买 我强烈建议您不要这样做。

finally 块应该用于资源清理或任何需要运行的类似功能,无论异常如何。

所有的异常处理都应该在 catch 块中完成,而不是 finally 块。

于 2013-03-20T13:25:05.643 回答
1

我在这里建议您将异常处理的详细信息提取到新方法中,并从必要的特定捕获块中调用这些方法以避免instanceof检查。这样做的好处是不使用instanceof,将异常处理代码保存在catch块中而不是 in 中finally,并且清楚地将共享异常处理代码与特定异常处理代码分开。是的,这三个块之间有一些共享代码catch,但这是一个清晰的代码行,这对我来说似乎可以接受。

try {
    // do work that uses resources and can generate any of several exceptions
} catch (SomeException1 e) {
    standardExceptionHandler(e);
    specificExceptionHandler1(e);
} catch (SomeException2 e) {
    standardExceptionHandler(e);
    specificExceptionHandler2(e);
} catch (Exception e) {
    standardExceptionHandler(e);
} finally {
    // this would include only code that is needed to cleanup resources, which is
    // what finally is supposed to do.
}
于 2013-03-20T16:04:58.003 回答