Java API中为我们提供了一个用于捕获线程内部运行时异常的接口。实现这个接口并给线程指定异常捕获器就可以达到目的。
public interface UncaughtExceptionHandler {
/**
* Method invoked when the given thread terminates due to the
* given uncaught exception.
*
Any exception thrown by this method will be ignored by the
* Java Virtual Machine.
* @param t the thread
* @param e the exception
*/
void uncaughtException(Thread t, Throwable e);
}
因为线程类的run()方法并不能抛出异常,所以如果不为线程指定UncaughtExceptionHandler,那么当遇到运行时异常的时候就会在控制台打印异常堆栈信息,并终止线程。
public class MyRunnable implements Runnable {
@Override
public void run() {
Integer.parseInt("ABC");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable(), "MyThread-1");
//thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
Exception in thread "MyThread-1" java.lang.NumberFormatException: For input string: "ABC"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at oschian.concurrency.section_07.MyRunnable.run(MyRunnable.java:9)
at java.lang.Thread.run(Thread.java:745)
首先我们实现一个线程异常处理器,需要重写uncaughtException方法。
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("ExceptionHandler: An exception has been captured.\n");
System.out.printf("Thread: %s %s %s\n", t.getName(), e.getClass(), e.getMessage());
}
}
接下来我们定义一个线程,在线程内部模拟一个运行时异常。使用setUncaughtExceptionHandler方法给这个线程指定异常处理器并启动线程。
public class MyRunnable implements Runnable {
@Override
public void run() {
Integer.parseInt("ABC");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable(), "MyThread-1");
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
查看控制台你会发现异常处理器捕获了运行时异常并处理。
ExceptionHandler: An exception has been captured.
Thread: MyThread-1 class java.lang.NumberFormatException For input string: "ABC"