为什么这个代码最后会出现然后阻塞?

时间:2017-03-26 08:02:44

标签: java exception-handling finally

package testing;

public class ExceptionHandling {
    public static void main(String[] args){
        try{
        int a=10;
        int b=0;
        int c=a/b;
        ExceptionHandling exp = null;
        System.out.println(exp);
        throw new NullPointerException();

        }catch(ArithmeticException e){
            System.out.println("arithmetic issue");
            throw new ArithmeticException();
        }
        catch(NullPointerException e){
            System.out.println("nullpointer");

        }
        finally{

            System.out.println("exception");
            //throw new ArithmeticException();
        }

    }

}

在控制台中我得到了这个:

arithmetic issue
exception
Exception in thread "main" java.lang.ArithmeticException
    at testing.ExceptionHandling.main(ExceptionHandling.java:15)

但是为什么它首先打印块语句然后捕获块语句?它应首先打印catch块语句,然后最后阻止语句。

4 个答案:

答案 0 :(得分:2)

控制台中的这一行:

Exception in thread "main" java.lang.ArithmeticException
    at testing.ExceptionHandling.main(ExceptionHandling.java:15)

未从catch块打印。在程序最终离开后打印出来。

以下是执行的方式。

  1. try中发生异常。
  2. catch抓住了这个例外。
  3. arithmetic issuecatch块打印。
  4. 下一行重新抛出该异常。
  5. 你的程序即将离开catch,但在它离开之前,它会执行finally块的代码。这就是你在控制台中看到单词exception的原因。这就是finally的工作原理。
  6. 最后,当程序最终离开此方法时,您会在控制台上看到实际的异常。

答案 1 :(得分:1)

它没有先运行,println的工作方式与异常输出同时发生。所以他们可以按各种顺序打印

答案 2 :(得分:1)

这是流程的方式:

  1. catch语句捕获异常,打印消息但又重新抛出异常
  2. 执行finally块,因此打印其消息
  3. 引发catch引发的异常,因为catch无法处理它

答案 3 :(得分:0)

thrown方法的异常main()将由JVM 处理 因为您已在ArithmeticException块中重新创建catch,并在thrown方法中重新main,所以 JVM抓住了您的ArithmeticException main()方法并在控制台上打印堆栈跟踪。

您的计划流程如下:

尝试块

(1)ArithmeticException thrown

(2)ArithmeticException阻止了catch阻止,重新创建了new ArithmeticExceptionthrown (由此main()方法)

(3)finally块已执行并打印给定文本

(4)此ArithmeticException方法抛出的 main()已被JVM捕获

(5) JVM打印了异常的堆栈跟踪

要更好地理解这个概念,只需throw来自不同方法的异常,并从我的main()抓住它,如下所示:

    //myOwnMethod throws ArithmeticException
    public static void myOwnMethod() {
        try{
            int a=10;
            int b=0;
            int c=a/b;
            throw new NullPointerException();
        } catch(ArithmeticException e){
            System.out.println("arithmetic issue");
            throw new ArithmeticException();
        }
        catch(NullPointerException e){
            System.out.println("nullpointer");
        }
        finally{
            System.out.println("exception");
        }
    }

    //main() method catches ArithmeticException
    public static void main(String[] args) {
        try {
            myOwnMethod();
        } catch(ArithmeticException exe) {
            System.out.println(" catching exception from myOwnMethod()::");
            exe.printStackTrace();
        }
    }

但是在你的情况下,你的main()抛出异常并且JVM捕获了异常。

相关问题