[英]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
紙架打印。 程序最終退出后打印。
執行方式如下。
try
發生異常。 catch
捕獲該異常。 catch
塊打印arithmetic issue
。 catch
,但是在它離開之前,它將最終執行block的代碼。 這就是為什么您在控制台中看到單詞exception
的原因。 這就是finally
設計成工作方式的方式。 它不會首先運行,所以println
工作方式與異常輸出並發。 因此它們可以按各種順序打印
流程如下:
catch
語句捕獲異常,打印消息,但也再次引發異常 finally
塊,因此打印了其消息 catch
提高,因為從catch
它沒有被處理,無論如何 異常thrown
通過main()
方法將被JVM進行處理 ,並因為你已經重新創建ArithmeticException
在catch
塊,並thrown
從它main
方法,那么JVM已經引起了你的ArithmeticException
被拋出main()
方法 ,並印在堆棧跟蹤安慰。
您的程序流程如下:
(1)try塊thrown
ArithmeticException
(2) ArithmeticException
已由catch
塊捕獲,並重新創建了一個new
ArithmeticException
並thrown
(通過此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.