java线程捕获异常(案例)

无法捕获的线程异常

public class ExceptionThread implements Runnable {



@Override
public void run() {
throw new RuntimeException();
}
public static void main(String[] args) {
try {
ExecutorService service = Executors.newCachedThreadPool();//new Handler()
service.execute(new ExceptionThread());
} catch (Exception e) {
// TODO: handle exception
System.out.println("无法捕获,执行不到。。。。");
}
}

}

--控制台输出

Exception in thread "pool-1-thread-1" java.lang.RuntimeException
at com.smallfan.thread.ExceptionThread.run(ExceptionThread.java:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

at java.lang.Thread.run(Thread.java:745)

修改后代码

public class ExceptionThread2 implements Runnable{


@Override
public void run() {
Thread thread = Thread.currentThread();
System.out.println("run.."+thread);
System.out.println("ex.."+thread.getUncaughtExceptionHandler());
throw new RuntimeException();
}



}

//通过uncaughtException来捕获异常

class Mycatch implements Thread.UncaughtExceptionHandler{


@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("e..."+e);
}

}
class Handler implements ThreadFactory{


@Override
public Thread newThread(Runnable r) {
System.out.println(this+" this new thread  ");
Thread t= new Thread(r);
t.setUncaughtExceptionHandler(new Mycatch());
System.out.println("e..."+t.getUncaughtExceptionHandler());
return t;
}

}

public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool(new Handler());//
service.execute(new ExceptionThread2());
}

--修改后控制台输出

com.smallfan.thread.Handler@4e25154f this new thread  
e...com.smallfan.thread.Mycatch@70dea4e
run..Thread[Thread-0,5,main]
ex..com.smallfan.thread.Mycatch@70dea4e
com.smallfan.thread.Handler@4e25154f this new thread  
e...com.smallfan.thread.Mycatch@21a20aa6
e...java.lang.RuntimeException

Thread.UncaughtExceptionHandler是java se5中的新接口,他提供在每个Thread对象都附着一个异常处理器

如:uncaughtException(Thread t, Throwable e)。会在线程因未捕获的异常临近死亡时被调用。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值