简述
当线程中出现异常时,我们可以使用Thread自带的方法进行全局捕获
方法
- setUncaughtExceptionHandler
捕获指定线程出现的异常
Thread t1 = new Thread(){
@Override
public void run() {
Object a = null;
a.toString();
}
};
t1.setName("线程t1");
t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("线程:" + t.getName() + " 出现了异常:");
e.printStackTrace();
}
});
t1.start();
- setDefaultUncaughtExceptionHandler
捕获所有线程出现的异常
Thread
.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("线程:" + t.getName() + " 出现了异常:");
e.printStackTrace();
}
});
Thread t1 = new Thread(){
@Override
public void run() {
Object a = null;
a.toString();
}
};
t1.setName("t1");
t1.start();
Thread t2 = new Thread(){
@Override
public void run() {
Object a = null;
a.toString();
}
};
t2.setName("t2");
t2.start();
网友评论