多线程:一个线程在运行时发生异常会怎么样?
Java中Throwable分為Exception和Error:?
出現(xiàn)Error的情況下,程序會(huì)停止運(yùn)行。?
Exception分為RuntimeException和非運(yùn)行時(shí)異常。?
非運(yùn)行時(shí)異常必須處理,比如thread中sleep()時(shí),必須處理InterruptedException異常,才能通過(guò)編譯。?
而RuntimeException可以處理也可以不處理,因?yàn)?strong>編譯并不能檢測(cè)該類異常,比如NullPointerException、ArithmeticException)和 ArrayIndexOutOfBoundException等。(運(yùn)行時(shí)異常在編譯階段是無(wú)法檢測(cè)出來(lái)的,非運(yùn)行時(shí)異常在編譯階段是可以檢測(cè)出來(lái)的,比如你使用了一個(gè)sleep()函數(shù),會(huì)強(qiáng)制要求你throws,并且try catch)
由此題目所訴情形下發(fā)生的應(yīng)該是RuntimeException,屬于未檢測(cè)異常,編譯器不會(huì)檢查該異常,可以處理,也可不處理。?
所以這里存在兩種情形:?
① 如果該異常被捕獲或拋出,則程序繼續(xù)運(yùn)行。?
② 如果異常沒(méi)有被捕獲該線程將會(huì)停止執(zhí)行。?
Thread.UncaughtExceptionHandler是用于處理未捕獲異常造成線程突然中斷情況的一個(gè)內(nèi)嵌接口。當(dāng)一個(gè)未捕獲異常將造成線程中斷的時(shí)候JVM會(huì)使用Thread.getUncaughtExceptionHandler()來(lái)查詢線程的UncaughtExceptionHandler,并將線程和異常作為參數(shù)傳遞給handler的uncaughtException()方法進(jìn)行處理
。
實(shí)例:?
1.未處理的RuntimeException,發(fā)生異常后程序停止運(yùn)行
public class Main1 {
? ? public static void main(String[] args){
? ? ? ? ? ? int x = 1;
? ? ? ? ? ? x = x / 0;
? ? ? ? ? ? System.out.println("x = "+x);
? ? }
}
輸出:
Exception in thread "main" java.lang.ArithmeticException: / by zero
? ? at microsoft2018.Main1.main(Main1.java:14)
?
2.程序處理RuntimeException,發(fā)生異常后繼續(xù)運(yùn)行
public class Main1 {
? ? public static void main(String[] args){
? ? ? ? try{
? ? ? ? ? ? int x = 1;
? ? ? ? ? ? x = x / 0;
? ? ? ? }catch(Exception e){
? ? ? ? ? ? System.out.println("除0錯(cuò)誤");
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ?System.out.println("繼續(xù)執(zhí)行");
? ? }
}
輸出:
除0錯(cuò)誤
java.lang.ArithmeticException: / by zero
? ? at microsoft2018.Main1.main(Main1.java:14)
繼續(xù)執(zhí)行
?
總結(jié)
以上是生活随笔為你收集整理的多线程:一个线程在运行时发生异常会怎么样?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。