【问题标题】:What happens when both catch block and finally block throw exception in Java?当 Java 中的 catch 块和 finally 块都抛出异常时会发生什么?
【发布时间】:2017-02-10 19:39:07
【问题描述】:

考虑一下我在一次采访中被问到的这个问题

public class Test_finally {
    private static int run(int input) {
        int result = 0;
        try { 
            result = 3 / input;
        } catch (Exception e) {
            System.out.println("UnsupportedOperationException");
            throw new UnsupportedOperationException("first");
        } finally {
            System.out.println("finally input=" + input);
            if (0 == input) {
                System.out.println("ArithmeticException");
                throw new ArithmeticException("second");
            }
        }

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

    public static void main(String[] args) {
        int output = Test_finally.run(0);
        System.out.println("  output=" + output);
    }
}

这个程序的输出抛出 ArithmeticException 而不是 UnsupportedOperationException

面试官只是问我如何让客户知道引发的原始异常类型是UnsupportedOperationException 而不是ArithmeticException。 我不知道

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    • 人们可能不会故意从finally 块中抛出异常,但各种事情都可能导致finally 块内发生未经检查(和意外)的异常。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多