线程中的异常处理

来源:互联网 发布:网络诈骗根本抓不到 编辑:程序博客网 时间:2024/04/29 18:45

/*在线程中,也即是在run()方法中是不允许throw exception,所有的异常必须在run()方法内进行处理
 * 对于checked exception,可以简单的用try/catch块进行处理就可以,但是对于unchecked exception
 * 处理的方式就稍微复杂一些。具体步骤如下
 *  =>首先定义一个类实现UncaughtExceptionHandler接口,在实现的方法中包含对异常的处理的逻辑和步骤
 *  =>定义线程执行结构和逻辑。这一步和普通的线程定义是一样的(就是创建线程的步骤)
 *  =>在开启线程之前,也就是在thread.start()方法之前,增加一个thread.setUncaughtExceptionHandler(第一步中定义的类的实例)
 *   语句来实现处理逻辑的注册。
 * 
 * 
 * */

package thread;import java.lang.Thread.UncaughtExceptionHandler;class ExceptionHanndlerThread implements UncaughtExceptionHandler{@Overridepublic void uncaughtException(Thread t, Throwable e) {// TODO Auto-generated method stubSystem.out.println("An Exception has been captured");System.out.println("Thread:"+t.getId());System.out.println("Exception:"+e.getClass().getName()+e.getMessage());System.out.println("Stack Trace:");e.printStackTrace(System.out);System.out.println("Thread Status:"+t.getState());}}class UncaughtExceptionCreate implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stub@SuppressWarnings("unused")int number = Integer.parseInt("ddd");}}public class ThreaduncaughtExceptionHanndler{public static void  main(String[] args){UncaughtExceptionCreate thredc = new UncaughtExceptionCreate();Thread thread = new Thread(thredc);thread.setUncaughtExceptionHandler(new ExceptionHanndlerThread());thread.start();}}



0 0
原创粉丝点击