簡體   English   中英

為什么此代碼首先出現在最后,然后是catch塊?

[英]Why this code is coming first in finally and then catch block?

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阻塞語句,然后再打印阻塞語句。

控制台中的這一行:

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

沒有從您的catch紙架打印。 程序最終退出后打印。

執行方式如下。

  1. try發生異常。
  2. catch捕獲該異常。
  3. catch塊打印arithmetic issue
  4. 下一行重新引發該異常。
  5. 您的程序將要離開catch ,但是在它離開之前,它將最終執行block的代碼。 這就是為什么您在控制台中看到單詞exception的原因。 這就是finally設計成工作方式的方式。
  6. 最后,當程序最終離開此方法時,您會在控制台上看到實際的異常。

它不會首先運行,所以println工作方式與異常輸出並發。 因此它們可以按各種順序打印

流程如下:

  1. catch語句捕獲異常,打印消息,但也再次引發異常
  2. 執行了finally塊,因此打印了其消息
  3. 在拋出的異常catch提高,因為從catch它沒有被處理,無論如何

異常thrown通過main()方法將被JVM進行處理 ,並因為你已經重新創建ArithmeticExceptioncatch塊,並thrown從它main方法,那么JVM已經引起了你的ArithmeticException被拋出main()方法 ,並印在堆棧跟蹤安慰。

您的程序流程如下:

(1)try塊thrown ArithmeticException

(2) ArithmeticException已由catch塊捕獲,並重新創建了一個new ArithmeticExceptionthrown (通過此main()方法)

(3) finally塊已經執行並打印給定的文本

(4) JVM捕獲了此main()方法引發的ArithmeticException

(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捕獲了該異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM