在Java中有兩種異常:java
當受檢查異常在線程的run方法中被拋出,咱們必須捕獲它並處理,由於run方法簽名沒有throws子句;當一個運行時異常在run方法中拋出,默認的行爲就是將異常棧中的信息打印到控制檯而後結束程序;ide
幸運的是,Java提供了在線程中捕獲和處理運行時異常的機制,從而避免了程序應爲運行時異常而終止;spa
接下來展現這種機制;線程
(1) 首先須要實現接口Thread.UncaughtExceptionHandler,code
public class ExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.printf("An exception has been captured\n"); System.out.printf("Thread: %s\n",t.getId()); System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage()); System.out.printf("Stack Trace: \n"); e.printStackTrace(System.out); System.out.printf("Thread status: %s\n",t.getState()); } }(2)建立線程,觸發一個運行時異常
public class Task implements Runnable { @Override public void run() { // trigger runtime exception int numero=Integer.parseInt("TTT"); } public static void main(String[] args) { Thread thread = new Thread(new Task()); //Handle runtime exception in thread thread.setUncaughtExceptionHandler(new ExceptionHandler()); thread.start(); } }一次運行結果:
An exception has been captured
Thread: 10
Exception: java.lang.NumberFormatException: For input string: "TTT"
Stack Trace:
java.lang.NumberFormatException: For input string: "TTT"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at com.sun.base.thread.A_d.Task.run(Task.java:10)
at java.lang.Thread.run(Thread.java:745)
Thread status: RUNNABLEorm
(1)實現接口Thread.UncaughtExceptionHandler對象
(2)爲線程設置異常處理屬性接口
當一個異常在線程中被拋出,而且沒有捕獲,JVM會檢查這個線程是否設置了對應異常處理Handler,若是設置了JVM調用這個Handler;若是沒有,程序打印堆棧信息而後退出;get
線程Thread還有一個方法setDefaultUncaughtExceptionHandler 能夠爲全部的線程對象設置一個默認的異常處理Handler;
input
當異常在線程中拋出,JVM首先檢查對應的線程是否有異常處理handler,若是沒有,JVM將會檢查ThreadGroup(後面記錄)的異常處理Handler,若是還不存在,JVM檢查默認的錯誤處理Handler,若是沒有設置,打印堆棧,退出程序;