run()方法不允许throw exception,因此所有的异常必须在run()方法内进行处理。
方式一:使用try-catch
package study.thread.exceptiontest;
/**
*
* 使用try-catch处理线程异常
*
*/
public class ExceptionHandle1 implements Runnable {
@Override
public void run() {
int num = 0;
try {
num = Integer.parseInt("TTT");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("num = " + num);
}
public static void main(String[] args) {
ExceptionHandle1 t1 = new ExceptionHandle1();
Thread thread = new Thread(t1);
thread.start();
}
}
执行结果如下
java.lang.NumberFormatException: For input string: "TTT"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at study.thread.exceptiontest.ExceptionHandle1.run(ExceptionHandle1.java:14)
at java.lang.Thread.run(Thread.java:748)
num = 0
方式二:使用Thread类中setUncaughtExceptionHandler()方法
在异常发生的时候,传入的UncaughtExceptionHandler接口实现类中的uncaughtException()方法会被调用。
package study.thread.exceptiontest;
import java.lang.Thread.UncaughtExceptionHandler;
/**
*
* 异常处理的方式,自定义实现
*
*/
public class UncaughtExceptionHandlerDemo implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("An exception has been captured");
System.out.printf("Thread: %s\n", t.getId());
System.out.printf("Exception: %s:%s\n", e.getClass().getName(), e.getMessage());
System.out.println("Stack Trace:");
e.printStackTrace(System.out);
System.out.printf("Thread status:%s\n", t.getState());
}
}
package study.thread.exceptiontest;
public class ExceptionHandle2 implements Runnable {
@Override
public void run() {
int num = Integer.parseInt("TTT");
System.out.println("num = " + num);
}
public static void main(String[] args) {
ExceptionHandle2 t1 = new ExceptionHandle2();
Thread thread = new Thread(t1);
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandlerDemo());
thread.start();
}
}
执行结果如下
An exception has been captured
Thread: 11
Exception: java.lang.NumberFormatException:For input string: "TTT"
Stack Trace:
java.lang.NumberFormatException: For input string: "TTT"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at study.thread.exceptiontest.ExceptionHandle2.run(ExceptionHandle2.java:7)
at java.lang.Thread.run(Thread.java:748)
Thread status:RUNNABLE