当catch阻塞并最终在Java中阻止抛出异常时会发生什么?

时间:2016-10-02 21:16:49

标签: java exception exception-handling try-catch try-catch-finally

考虑一下我在面试中被问到的这个问题

ArithmeticException

此计划的输出会导致UnsupportedOperationException而不是UnsupportedOperationException

访谈员只是问我如何让客户知道提出的原始异常类型为ArithmeticException而不是{{1}}。 我不知道

1 个答案:

答案 0 :(得分:1)

永远不要返回或扔进一个finally块。作为面试官,我希望得到答案。

一位寻找细微技术细节的蹩脚面试官可能希望您知道Exception.addSuppressed()。您实际上无法在finally块中读取抛出的异常,因此您需要将其存储在throw块中以重用它。

类似的东西:

private static int run(int input) throws Exception {
    int result = 0;
    Exception thrownException = null;
    try {
        result = 3 / input;
    } catch (Exception e) {
        System.out.println("UnsupportedOperationException");
        thrownException = new UnsupportedOperationException("first");
        throw thrownException;
    } finally {
        try {
            System.out.println("finally input=" + input);
            if (0 == input) {
                System.out.println("ArithmeticException");
                throw new ArithmeticException("second");
            }
        } catch (Exception e) {
            // Depending on what the more important exception is,
            // you could also suppress thrownException and always throw e
            if (thrownException != null){
                thrownException.addSuppressed(e);
            } else {
                throw e;
            }
        }
    }

    System.out.println("end of method");
    return result * 2;
}