有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否像重新引发相同的异常?

当我执行这段代码时,我得到了“最终”

public class Tester {
    static void method() throws Exception {
        throw new Exception();
    }

    public static void main(String... args) {
        try {
            method();
        } catch (Throwable th) { 
            try {
                new Exception();
            } catch (Exception e) {
                System.out.print("Exception");
            } finally {
                System.out.print("finally");
            }
        }
    }
}

无法确定执行流程


共 (2) 个答案

  1. # 1 楼答案

    上述代码的输出将是

    finally
    

    如果您想知道为什么输出不正确

    Exception finally
    

    那是因为在下面的代码行中

    try {
            new Exception();
        }
    

    您只是声明了一个新的Exception对象,并不是真的抛出它

    如果希望输出为Exception finally,则必须通过放置throw new Exception();而不是new Exception();来抛出该对象

    然后,代码将如下所示:

    public class HelloWorld{
        static void method() throws Exception{ throw new Exception(); }
    
        public static void main(String... args){
            try{method();}
            catch(Throwable th)
            {
                try{ throw new Exception(); }
                catch(Exception e){System.out.print("Exception");}
                finally{System.out.print("finally");}    
            }
        }
    } 
    

    输出

    Exceptionfinally
    
  2. # 2 楼答案

    如果代码try块中是否引发异常,则将执行finally