捕获异常

1、因为线程的本质特性,一般无法捕获从线程逃逸的异常。异常逃出任务run方法,会向外传播到控制台。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ExceptionThread implements Runnable {
	
	public void run(){
		throw new RuntimeException();//抛出的异常在main中用try-catch无法捕获
	}
	public static void main(String[] args) {
		/*ExecutorService executorService=Executors.newCachedThreadPool();
		executorService.execute(new ExceptionThread());*/
		try{
			ExecutorService executorService=Executors.newCachedThreadPool();
			executorService.execute(new ExceptionThread());
		} catch (RuntimeException e) {
			System.out.println("Exception has been handled");
		}
	}
}
/*Exception in thread "pool-1-thread-1" java.lang.RuntimeException
at ExceptionThread.run(ExceptionThread.java:8)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)*/
2、现在,可以用Executor来捕获异常。

在程序中添加跟踪机制。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;


public class CaptureUncaughtException {
	static public class ExceptionThread implements Runnable{
		public void run(){
			Thread thread=Thread.currentThread();
			System.out.println("run by "+thread);
			System.out.println("eh= "+thread.getUncaughtExceptionHandler());
			throw new RuntimeException();
		}
	}
	
	static public class MyUncaughtExceptionHandler implements 
	Thread.UncaughtExceptionHandler{
		public void uncaughtException(Thread t,Throwable e){
			System.out.println("caught "+e);
		}
	}
	
	static public class HandleThreadFactory implements ThreadFactory{
		public  Thread newThread(Runnable r) {
			System.out.println(this+" creating new thread");
			Thread thread=new Thread(r);
			thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
			System.out.println("eh= "+thread.getUncaughtExceptionHandler());
			return thread;
		}
	}
	public static void main(String[] args) {
		ExecutorService executorService=Executors.newCachedThreadPool(
				new HandleThreadFactory());
		executorService.execute(new ExceptionThread());
	}

}
/*CaptureUncaughtException$HandleThreadFactory@165a3c2 creating new thread
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@11e0c13
run by Thread[Thread-0,5,main]
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@11e0c13
CaptureUncaughtException$HandleThreadFactory@165a3c2 creating new thread
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@1242b11
caught java.lang.RuntimeException*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值