如下代码
public class ExceptionThread {
public static void main(String[] args) throws InterruptedException {
try {
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
}catch (RuntimeException e){
System.out.println("---"+e);
}
}
}
class ThreadException implements Runnable{
@Override
public void run() {
throw new RuntimeException();
}
}
运行结果
模拟五个线程,每个线程均抛出异常。在主线程中进行异常捕获。但是根据结果看来异常并未被捕获,没有进入catch块中 。这是因为异常是发生在子线程中的,而try-catch块只能捕获的当前线程的异常。所以在主线程中加入的异常捕获机制并不能进行异常的处理。
想要解决子线程的异常问题,有两种解决方式
方式一: 在子线程中捕获
class ThreadException implements Runnable{
@Override
public void run() {
try {
throw new RuntimeException();
}catch (RuntimeException e){
System.out.println("-- "+e);
}
}
}
运行结果:
方式二:自定义异常类实现 UncaughtExceptionHandler 接口
class TheCustomException implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.WARNING,"线程异常终止了"+t.getName(),e);
System.out.println("线程名称"+t.getName()+" 异常原因"+e);
}
}
然后再主线程中设置异常的处理机制
public static void main(String[] args) throws InterruptedException {
//自定义的异常处理机
Thread.setDefaultUncaughtExceptionHandler(new TheCustomException());
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
Thread.sleep(100);
new Thread(new ThreadException()).start();
}
运行结果: