java - 在 Java 中,当 catch block 和 finally block 都抛出异常时会发生什么?

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

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

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。 我不知道

最佳答案

切勿在 finally block 中返回或抛出。作为面试官,我希望得到这样的答案。

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

类似这样的事情:

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;
}

关于java - 在 Java 中,当 catch block 和 finally block 都抛出异常时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821792/

相关文章:

java - 如何在 Spring 中处理 DataIntegrityViolationException?

Java:java.lang.NumberFormatException

haskell - 什么时候可以保证 MVar 操作不间断?

java - 操纵gs spring项目

java - 在java中创建临时文件夹

java - 在编译时,JVM 如何发现不必要的 CloneNotSupportedException 而不是 Exception?

java - java如何捕获java内部的退出代码?

hibernate - Quartz 作业因 StaleObjectStateException 异常而停止执行

Java 通配符不允许类型转换

java - 如何选择颜色