现在的位置: 首页 > 综合 > 正文

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

2014年01月31日 ⁄ 综合 ⁄ 共 1449字 ⁄ 字号 评论关闭

在并发的情况下,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();
	}
}

抱歉!评论已关闭.