关于未捕获异常(Uncaught Exception)的处理
2015-10-08 10:30
756 查看
我们经常使用try..catch进行异常处理,但是对于Uncaught Exception是没办法捕获的。对于这类异常如何处理呢?
回顾一下thread的run方法,有个特别之处,它不会抛出任何检查型异常,但异常会导致线程终止运行。这非常糟糕,我们必须要“感知”到异常的发生。比如某个线程在处理重要的事务,当thread异常终止,我必须要收到异常的报告(email或者短信)。
在jdk 1.5之前貌似无法直接设置thread的Uncaught Exception Handler(具体未验证过),但从1.5开始可以对thread设置handler。
1. As the handler for a particular thread
当 uncaught exception 发生时, JVM寻找这个线程的异常处理器. 可以使用如下的方法为当前线程设置处理器
2. As the handler for a particular thread group
如果这个线程属于一个线程组,且线程级别并未指定异常处理器(像上节As the handler for a particular thread中那样),jvm则试图调用线程组的异常处理器。
线程组(ThreadGroup)实现了Thread.UncaughtExceptionHandler接口,所以我们只需要在ThreadGroup子类中重写实现即可
java.lang.ThreadGroup 类uncaughtException默认实现的逻辑如下:
如果父线程组存在, 则调用它的uncaughtException方法.
如果父线程组不存在, 但指定了默认处理器 (下节中的As the default handler for the application), 则调用默认的处理器
如果默认处理器没有设置, 则写错误日志.但如果 exception是ThreadDeath实例的话, 忽略。
对应JDK的源码:
3. As the default handler for the application (JVM)
不写了,打字太累,什么时候能有好用的语音输入editor.
回顾一下thread的run方法,有个特别之处,它不会抛出任何检查型异常,但异常会导致线程终止运行。这非常糟糕,我们必须要“感知”到异常的发生。比如某个线程在处理重要的事务,当thread异常终止,我必须要收到异常的报告(email或者短信)。
在jdk 1.5之前貌似无法直接设置thread的Uncaught Exception Handler(具体未验证过),但从1.5开始可以对thread设置handler。
1. As the handler for a particular thread
当 uncaught exception 发生时, JVM寻找这个线程的异常处理器. 可以使用如下的方法为当前线程设置处理器
public class MyRunnable implements Runnable { public void run() { // Other Code Thread.currentThread().setUncaughtExceptionHandler(myHandler); // Other Code } }
2. As the handler for a particular thread group
如果这个线程属于一个线程组,且线程级别并未指定异常处理器(像上节As the handler for a particular thread中那样),jvm则试图调用线程组的异常处理器。
线程组(ThreadGroup)实现了Thread.UncaughtExceptionHandler接口,所以我们只需要在ThreadGroup子类中重写实现即可
public class ThreadGroup implements Thread.UncaughtExceptionHandler
java.lang.ThreadGroup 类uncaughtException默认实现的逻辑如下:
如果父线程组存在, 则调用它的uncaughtException方法.
如果父线程组不存在, 但指定了默认处理器 (下节中的As the default handler for the application), 则调用默认的处理器
如果默认处理器没有设置, 则写错误日志.但如果 exception是ThreadDeath实例的话, 忽略。
对应JDK的源码:
public void uncaughtException(Thread t, Throwable e) { if (parent != null) { parent.uncaughtException(t, e); } else { Thread.UncaughtExceptionHandler ueh = Thread.getDefaultUncaughtExceptionHandler(); if (ueh != null) { ueh.uncaughtException(t, e); } else if (!(e instanceof ThreadDeath)) { System.err.print("Exception in thread \"" + t.getName() + "\" "); e.printStackTrace(System.err); } } }
3. As the default handler for the application (JVM)
Thread.setDefaultUncaughtExceptionHandler(myHandler);
不写了,打字太累,什么时候能有好用的语音输入editor.
相关文章推荐
- php 文件操作类
- Git常用命令
- minihomepage.exe 百度视频迷你主页
- 本机运行.net 2.0项目报错,解决方案
- Object.wait()与Object.notify()的用法
- 【Android】 NFC课件
- 记录几次发布存在的问题
- iOS ---AFN--- 监测网络状态
- Gradle tip #2: understanding syntax
- 华为手机连不上adb解决方法
- mysql处理高并发,防止库存超卖
- 9月29日全球域名商(国际域名)解析量排行榜TOP20
- FineReport 报表工具的使用与集成
- 在Object-C中使用@property和@synthesize的区别
- Dialog使用自定义的样式
- Unity 贝塞尔曲线
- 【吐槽】gist.github.com疑遭中间人攻击
- Alerta
- windows下使用MinGW+msys编译ffmpeg
- android版本与API对应的意义何在