java中对于多线程程序的捕获异常的方案

在并发的情况下,try{}catch{Exception ex}不能捕获一般的异常处理,这会导致在异常产生时会直接将异常输出到控制台或者是用户界面,在java5中加入了一些接口来解决这个问题,下面为简单的事例

package com.eric.concurrency;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个程序主要掩饰了在程序中队Runnable异常的捕获方法
 * 
 * @author Eric
 * 
 */
public class ExceptionThread {
	
	public static void main(String[] args) {
		try {
			CatchException.catchExceptionByUncaughtExceptionHandler();
			System.out.println("************************************");
			// CatchException.catchExceptionByCatch();
		} catch (Exception ex) {
			// ex.printStackTrace();
		}
	}
}

class ExceptionRunnable implements Runnable {
	public void run() {
		throw new RuntimeException("Throw By Runnable");
	}
	
}

// 用普通的catch方法捕获
class CatchException {
	public static void catchExceptionByCatch() {
		ExecutorService es = Executors.newCachedThreadPool();
		es.execute(new ExceptionRunnable());
		
	}
	
	/*
	 * use try{} catch{} block can't catch exception from Runnable,to solve the
	 * problem. Thread.UncaughtExceptionHandler is a new interface in Java SE5;
	 * it allows you o attach an exception handler to each Thread object.
	 * Thread.UncaughtExceptionHandler.uncaughtException( ) is automatically
	 * called when that thread is about to die from an uncaught exception.
	 */
	public static void catchExceptionByUncaughtExceptionHandler() {
		Thread t = new Thread(new ExceptionRunnable());
		t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				System.out.println("Exception:" + e.getMessage() + " was catched");
			}
		});
		t.start();
	}
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值