java多线程系列四之线程异常的处理
run方法不允许throw exception,所有异常必须在run方法内进行处理。
public void setUncaughtExceptionHandler(UncaughtExceptionHandler paramUncaughtException)
{
checkAccess();
this.uncaughtExceptionHandler=paramUncaughtException;
}
而UncaughtExceptionHandler则是一个接口,所以我们需要实现它才可以使用。它的声明如下:
public static abstract interface UncaughtExceptionHandler
{
public abstract void uncaughtException(Thread paramThread,Throwable paramThrowable);
}
下面我们按此步骤实现一个实例。
首先实现 UncaughtExceptionHandler接口
import java.lang.Thread.UncaughtExceptionHandler;
public class UnCheckExceptionHandler implements UncaughtExceptionHandler{
public void uncaughtException(Thread t,Throwable e){//Throwable是所有异常的父类
System.out.println("An unchecked exception has been capture");
System.out.printf("Thread:%s\n",t.getId());
//System.out.println("Thread:"+t.getId());
System.out.printf("Exception:%s: %s\n",e.getClass().getName(),e.getMessage());
//System.out.println("Exception:"+e.getClass().getName()+":"+e.getMessage());
System.out.printf("Stack Trace:\n");
//System.out.println("Stack Trace:");
e.printStackTrace(System.out);//输出堆栈跟踪信息到控制台
System.out.printf("Thread status:%s\n",t.getState());
}
}
这里我们添加的异常处理逻辑很简单,只是把线程的信息和异常信息都打印出来
然后,定义线程的内容,这里,我们故意让该线程产生一个unchecked exception:
public class ExceptionThread implements Runnable{
public void run(){
int num=Integer.parseInt("UncheckExceptionCreat");//出现错误的地方
}
}
现在,把创建线程和注册处理逻辑部分补上。
public class TreadTest{
public static void main(String[] args) {
try{
ExceptionThread task=new ExceptionThread();
Thread thread=new Thread(task,"ExceptionHappen");
thread.setUncaughtExceptionHandler(new UnCheckExceptionHandler());
thread.start();
Thread.currentThread().sleep(1000L);//这个Checked Exception ,我们必须有处理代码。就是下面的InterruptedExcetion
System.out.println("主线程输出");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
运行结果
把// thread.setUncaughtExceptionHandler(new UnCheckExceptionHandler());注释掉,看看什么结果