为什么代码没有打印 "finally" 之后的行? (Java)

Why didn't the code printed the line after "finally"? (Java)

我有一个带有 try 和 catch 块的方法,finally 语句之后的代码没有打印("end of a" 行)。

该方法抛出异常,我怀疑这就是原因。 是行

的原因
System.out.println("end of a"); 

因为异常没有打印?

代码如下:

Test Class:

    public class Test
{
    Integer num;
    public Test(){
        this(0) ;
        System.out.println("Test constructor1 ");
    }
    public Test(int i){
        if (i>0) num = new Integer(i) ;
        System.out.println("Test constructor2 ");
    }
    public void a() throws Exception{
        try{
            if (num.intValue() > 0)
                System.out.println("num = "+num.intValue());
            System.out.println("executing a ");
            throw new Exception();
        }catch (Exception e){
            System.out.println("exception caught in a");
            if (e instanceof NullPointerException) throw e;
        }
        finally{
            System.out.println("finally in a");
        }
        System.out.println("end of a");
    }
}

Main Class:

public class MainTest2{
    public static void main(String args[]){
        try{
            Test t2 = new Test();
            t2.a();
            System.out.println("executing main1 ");
        }catch (Exception e){
            System.out.println("exception caught in main");
        }
        System.out.println("ending main ");
    }
}

异常的主要原因是NullPointerException由于num.intValue()造成的。
所以当异常出现时 System.out.println("finally in a"); 被执行。
在此之后,由于 e 实际上是 NPE 的实例,因此代码 returns 直接执行他的代码段 if (e instanceof NullPointerException) throw e;
最后一个 sysout 永远不会执行。

循序渐进:

  1. 当你在t2中调用a()时,t2num的值是null或者没有设置,换句话说
  2. 如果你 运行 if (num.intValue() > 0) 它会创建一个 NullPointerException(原因见第 1 步)
  3. 所以发生的异常会触发 try 并跳入 catch 块并通过 e 给出 NPEcatch
  4. catch 块测试 e 中的 NPE,这是真的,因此 throw e 将异常传递给下一个实例
  5. 正在执行 a() 中的 finally
  6. 程序离开 try-catch-finally 块,同时从第 4 步打开未处理的异常
  7. 第 6 步触发 a() 声明中对 throws Exception 的要求,因此 a() 停止执行,returns main()
  8. 现在 main() 负责异常, 运行ning

结论:
程序从未到达 System.out.println("end of a"); 行,因为它 运行 之前进入未处理的异常,抛出异常并在该行之前停止执行 a()

(抱歉出现拼写或语法错误 :))