捕获线程的异常

[TOC]

多线程之运行线程异常捕获

单个线程异常捕获

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @description: 线程异常捕捉
* @author: Administrator
* @create: 2019-12-23 22:22
**/
public class ThreadException {

public static void main(String[] args) {

//线程抛出异常
//thread1();
//捕获异常
thread2();


}

static void thread1(){
Thread thread = new Thread(() -> {
try {
Thread.sleep(2_000);
int i = 10/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
});

thread.start();
}


static void thread2(){
Thread thread = new Thread(() -> {
try {
Thread.sleep(2_000);
int i = 10/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
});

//输出异常信息
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println(t);
System.out.println(e);
});
thread.start();
}
}

thread1()方法运行结果

在这里插入图片描述
捕获线程异常使用 setUncaughtExceptionHandler(Thread t,Exception e)方法捕捉异常信息返回,然后再进行处理

thread1()方法运行结果
在这里插入图片描述

线程池捕捉异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ThreadPoolException {

public static void main(String[] args) {

//设置异常处理器
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());

//线程池
ExecutorService executorService = Executors.newCachedThreadPool();

executorService.execute(new ThreadTask());


executorService.shutdown();

}
}

异常处理器

1
2
3
4
5
6
7
8
9
10
11
12
class MyUncaughtExceptionHandler  implements Thread.UncaughtExceptionHandler {

@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到异常 : 线程名[" + t.getName() + "], 异常名[" + e + "]");

// 异常栈的信息
e.printStackTrace();

// TODO ... 如果对异常还需要做特殊处理,可以在此处继续实现处理方法
}
}

自定义抛出异常的线程

1
2
3
4
5
6
7
8
9
10
11
12
class ThreadTask implements Runnable {
@Override
public void run() {

//运行异常

System.out.println(Thread.currentThread().getName());
System.out.println("异常被谁处理:" + t.getUncaughtExceptionHandler());

throw new RuntimeException();
}
}

异常捕获

在这里插入图片描述