java多线程异常机制-UncaughtExceptionHandler

有没有发生过这样的情况,你写的工作线程莫名其妙的挂了,不知道啥原因了,因为异常的时候只会把stack trace打在控制台上,最后只能在能加try catch 的地方都给加上。

我们已经知道,Java中有两种异常,即已检测异常和未检测异常。

受检异常(checked exception):在编译时需要检查的异常,需要用try-catch或throws处理。在java中主要指除了Error和RuntimeException之外的异常

非受检异常(unchecked exception):不需要在编译时处理的异常。在java中派生于Error和RuntimeException的异常都是unchecked exception,其他都是checked exception
 

package com.caojiulu.runnable1;

class Task implements Runnable {
	public static void main(String[] args) {
		Task task = new Task();
		Thread thread1 = new Thread(task);
		thread1.start();
	}

	public void run() {
		System.out.println(Integer.parseInt("111"));
		System.out.println(Integer.parseInt("222"));
		System.out.println(Integer.parseInt("666"));
		System.out.println(Integer.parseInt("caojiulu")); 
		System.out.println(Integer.parseInt("888"));
		System.out.println(Integer.parseInt("999"));
	}

}

运行情况:

使用UncaughtExceptionHandler之后

package com.caojiulu.runnable1;

import java.lang.Thread.UncaughtExceptionHandler;

public class ExceptionHandler implements UncaughtExceptionHandler{

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		// TODO Auto-generated method stub
		System.out.println("发生了错误");
	}

}
public static void main(String[] args) {
		Task task = new Task();
		Thread thread1 = new Thread(task);
		thread1.setUncaughtExceptionHandler(new ExceptionHandler());
		thread1.start();
	}

运行结果:

很明显的可以看到,捕获了对应的异常。

我的理解是

使用catch捕获异常时,异常不会向上传递给上一级调用者;

使用uncaughtExceptionhandler会对于异常处理之后返回给上一级调用者,导致程序没有正常结束

文章参考链接:http://www.importnew.com/14434.html

猜你喜欢

转载自blog.csdn.net/a1173537204/article/details/88390437