併發編程實戰 1.7. 處理運行時異常 - setUncaughtExceptionHand()

在java中有兩種異常:

1. Checked Exception(非運行時異常):這種異常必須在方法的throws語句中指定,或者在方法體內使用try/catch塊捕獲,例如: IOException和 ClassNotFoundException。java

2. UncheckedException(運行時異常):這種異常因爲出現的場景很是多,因此即不須要方法指定,也不須要捕獲,例如:NumberFormatException。jvm

run()方法不支持throws語句

run()方法不支持throws語句,因此當運行時異常從run()方法中拋出時,默認行爲是在控制檯輸出堆棧記錄而且退出程序。可是,使用 setUncaughtExceptionHand()方法能夠捕獲及處理運行時異常。ide

範例:1. 建立一個進程進行計算後,出現運行時異常;2. 在異常處理類中處理捕獲到的運行時異常;測試

package com.rr.concurrent.chapter1.recipe8.test;

/**
 * Created by isaac_gu on 2016/5/11.
 * 1. 建立一個進程進行計算後,出現運行時異常;
 */
public class Task implements Runnable {

    @Override
    public void run() {
        int a = 10;
        int b = 0;
        int c = a / b;
        System.out.println("c : " + c);
    }
}

異常處理:spa

package com.rr.concurrent.chapter1.recipe8.test;

/**
 * Created by isaac_gu on 2016/5/11.
 * 2. 在異常處理類中處理捕獲到的運行時異常;
 */
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("1. %s 線程出現了異常!\n", t.getName());
        System.out.printf("2. Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
        System.out.printf("3. Stack Trace: \n");
        e.printStackTrace(System.out);
        System.out.printf("4. Thread status: %s\n", t.getState());
    }
}

測試類:線程

package com.rr.concurrent.chapter1.recipe8.test;

import java.util.concurrent.TimeUnit;

/**
 * Created by isaac_gu on 2016/5/11.
 * 範例:1. 建立一個進程進行計算後,出現運行時異常;2. 在異常處理類中處理捕獲到的運行時異常;
 */
public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Task());
        //設置異常處理類
        thread.setUncaughtExceptionHandler(new MyExceptionHandler());
        thread.start();

        //兩秒後主線程結束
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主線程結束!");

    }
}

運行結果:code

1. Thread-0 線程出現了異常!
2. Exception: java.lang.ArithmeticException: / by zero
3. Stack Trace: 
java.lang.ArithmeticException: / by zero
	at com.rr.concurrent.chapter1.recipe8.test.Task.run(Task.java:13)
	at java.lang.Thread.run(Thread.java:745)
4. Thread status: RUNNABLE
主線程結束!

Thread 類還有一個處理未捕獲到的異常,靜態方法 setDefaultUncaughtExcptionHandler();orm

當線程拋出一個異常的時候:

首先,它查找線程設置的異常處理器(UncaughtExcptionHandler );進程

若是沒有,查找線程組(ThreadGroup)的異常處理器;ip

若是還找不到,將查找默認的異常處理器( DefaultUncaughtExcptionHandler );

若是沒有一個處理器存在,jvm打印異常到控制檯,並退出程序。

相關文章
相關標籤/搜索