首页 > 解决方案 > 内部 catch 块引发的异常会发生什么

问题描述

当我运行以下 java 代码时,我得到的输出为“ACDF”。有人可以解释一下如何处理最里面的 catch 块中抛出的运行时异常吗?(我期待它在“E”被附加到结果字符串变量的块中处理)

public class HelloWorld {

    public static String someFunction() {
        String result = "";
        String str = null;

        try {
            try {
                try {
                    result += "A";
                    str.length();
                    result += "B";
                } catch (NullPointerException e) {
                    result += "C";
                    throw new RuntimeException(); // where this one goes????

                } finally {
                    result += "D";
                    throw new Exception();
                }
            } catch (RuntimeException e) {
                result += "E";
            }
        } catch (Exception e) {
            result += "F";
        }


        return result;
    }

    public static void main(String[] args) {
        System.out.println(someFunction());
    }
}

标签: javaexception

解决方案


finally总是执行(忽略整个 JVM 死掉的特殊边缘情况)。我不是在开玩笑,即使你return,也会在之前被处决return

请参阅是否总是在 Java 中执行 finally 块?详情。

所以当你抛出时RuntimeException,你将首先执行finally附加的那个D

既然你扔Exception在那里,你现在会碰到catch (Exception e)块,因为catch (RuntimeException e)不匹配。因此,您追加F.

因此,结果是ACDF


注释代码:

public class HelloWorld {

    public static String someFunction() {
        String result = "";
        String str = null;

        try {
            try {
                try {
                    result += "A";
                    str.length(); // throws NullPointerException
                    result += "B";
                } catch (NullPointerException e) { // continue here
                    result += "C";
                    throw new RuntimeException();

                } finally { // finally is always executed
                    result += "D";
                    throw new Exception(); // throwing this
                }
            } catch (RuntimeException e) { // does not match
                result += "E";
            }
        } catch (Exception e) { // matches, continue here
            result += "F";
        } // cool, all done


        return result; // returning ACDF
    }

    public static void main(String[] args) {
        System.out.println(someFunction());
    }
}

推荐阅读