2017-03-26 20 views
1
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塊語句,然後再打印塊語句。

+1

你的輸出先打印'catch'塊,然後打印'finally'。爲什麼你認爲這是打印否則。 – Codebender

+1

查看此答案。 [鏈接](http://stackoverflow.com/questions/3109353/what-c​​omes-first-finally-or-catch-block)。另外,你不需要在try塊本身中拋出異常。 – budthapa

回答

0

它不首先運行,println工作的方式與異常輸出同時發生。所以他們可以打印各種順序

+0

該輸出與執行順序一致。在問題中沒有觀察到「各種命令」。 – Andreas

+0

@Andreas「這個輸出與執行順序一致」這是不正確的,我已經運行了上面的確切代碼並且[this](http://imgur.com/DdDYNyB)(「exception」打印在錯誤處理),但在這種情況下,我的答案也不是真的。我的意思是執行順序的確如他所說。 – MaMadLord

1

這是流程如何去:

  1. catch聲明捕捉異常,打印消息,但執行finally塊還拋出異常再次
  2. ,所以打印其消息
  3. catch拋出的異常升高,因爲從catch它沒有被處理,無論如何
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,但在離開之前,它會執行最後一個程序塊的代碼。這就是爲什麼你在控制檯中看到字exceptionfinally就是這樣設計的。
  6. 最後,當程序最終離開這個方法時,最後你會在控制檯上看到實際的異常。
+0

非常感謝您的解釋。 –

0

例外thrown通過main()方法將被JVM和 處理,因爲你已經從main方法則JVM已經引起重新在catchArithmeticExceptionthrown它你ArithmeticExceptionmain()方法拋出並在控制檯上打印堆棧跟蹤。

你的程序流程如下:

(1)ArithmeticExceptionthrown由try塊

(2)ArithmeticExceptioncatch塊和已經陷入重新創建一個newArithmeticExceptionthrown(由這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已經發現了異常。

相關問題