java 捕获运行时异常_Java并发编程初级篇(七):捕获线程中的运行时异常

Java API中为我们提供了一个用于捕获线程内部运行时异常的接口。实现这个接口并给线程指定异常捕获器就可以达到目的。

public interface UncaughtExceptionHandler {

/**

* Method invoked when the given thread terminates due to the

* given uncaught exception.

*

Any exception thrown by this method will be ignored by the

* Java Virtual Machine.

* @param t the thread

* @param e the exception

*/

void uncaughtException(Thread t, Throwable e);

}

因为线程类的run()方法并不能抛出异常,所以如果不为线程指定UncaughtExceptionHandler,那么当遇到运行时异常的时候就会在控制台打印异常堆栈信息,并终止线程。

public class MyRunnable implements Runnable {

@Override

public void run() {

Integer.parseInt("ABC");

}

public static void main(String[] args) {

Thread thread = new Thread(new MyRunnable(), "MyThread-1");

//thread.setUncaughtExceptionHandler(new ExceptionHandler());

thread.start();

}

}

Exception in thread "MyThread-1" java.lang.NumberFormatException: For input string: "ABC"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:492)

at java.lang.Integer.parseInt(Integer.java:527)

at oschian.concurrency.section_07.MyRunnable.run(MyRunnable.java:9)

at java.lang.Thread.run(Thread.java:745)

首先我们实现一个线程异常处理器,需要重写uncaughtException方法。

public class ExceptionHandler implements Thread.UncaughtExceptionHandler {

@Override

public void uncaughtException(Thread t, Throwable e) {

System.out.printf("ExceptionHandler: An exception has been captured.\n");

System.out.printf("Thread: %s %s %s\n", t.getName(), e.getClass(), e.getMessage());

}

}

接下来我们定义一个线程,在线程内部模拟一个运行时异常。使用setUncaughtExceptionHandler方法给这个线程指定异常处理器并启动线程。

public class MyRunnable implements Runnable {

@Override

public void run() {

Integer.parseInt("ABC");

}

public static void main(String[] args) {

Thread thread = new Thread(new MyRunnable(), "MyThread-1");

thread.setUncaughtExceptionHandler(new ExceptionHandler());

thread.start();

}

}

查看控制台你会发现异常处理器捕获了运行时异常并处理。

ExceptionHandler: An exception has been captured.

Thread: MyThread-1 class java.lang.NumberFormatException For input string: "ABC"

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值