java多线程的异常

首先是关于异常:

1
2
3
4
5
6
class ThreadTest2 implements Runnable{
@Override
public void run() {
System.out.println(1 / 0);
}
}

如果要捕捉这样的异常,外部是捕捉不到的

1
2
3
4
5
6
try{
Thread temp=new Thread(new ThreadTest2());
temp.start();
}catch (Exception e){
System.out.println("外部");
}

可以在run方法里面捕捉

1
2
3
4
5
6
7
8
9
10
class ThreadTest2 implements Runnable{
@Override
public void run() {
try {
System.out.println(1 / 0);
}catch (Exception e){
System.out.println("内部");
}
}
}

但是这样并不是很好的解决方法,虽然可以捕捉到,正常应该是实现UncaughtExceptionHandler接口

1
2
3
4
5
6
7
try{
Thread temp=new Thread(new ThreadTest2());
temp.setUncaughtExceptionHandler((thread,throwable)-> System.out.println("set"));
temp.start();
}catch (Exception e){
System.out.println("外部");
}

就可以捕捉到了.