Java线程中的异常处理

在线程中,也即是在run()方法中是不允许throw exception,所有的异常必须在run()方法内进行处理对于checked exception,可以简单的用try/catch块进行处理就可以,但是对于unchecked exception处理的方式就稍微复杂一些。具体步骤如下

  1. =>首先定义一个类实现UncaughtExceptionHandler接口,在实现的方法中包含对异常的处理的逻辑和步骤
  2. =>定义线程执行结构和逻辑。这一步和普通的线程定义是一样的(就是创建线程的步骤)
  3. =>在开启线程之前,也就是在thread.start()方法之前,增加一个thread.setUncaughtExceptionHandler(第一步中定义的类的实例)语句来实现处理逻辑的注册。
package thread;


import java.lang.Thread.UncaughtExceptionHandler;


class ExceptionHanndlerThread implements UncaughtExceptionHandler{


	@Override
	public void uncaughtException(Thread t, Throwable e) {
		// TODO Auto-generated method stub
		System.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 {


	@Override
	public 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();
	}
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值