【问题标题】:What happens to exception raised by inner catch block [duplicate]内部catch块引发的异常会发生什么[重复]
【发布时间】:2020-06-25 16:39:47
【问题描述】:

当我运行以下 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());
    }
}

【问题讨论】:

    标签: java exception


    【解决方案1】:

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

    详情请见Does a finally block always get executed in Java?

    所以当你抛出RuntimeException时,你将首先执行附加Dfinally

    由于您将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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多