记不得在哪里看到的代码,可以处理到线程中抛出的RuntimeException:
public class ApplicationLoader extends ThreadGroup
{
private ApplicationLoader()
{
super("ApplicationLoader");
}
public static void main(String[] args)
{
Runnable appStarter = new Runnable()
{
public void run()
{
//invoke your application (i.e.MySystem.main(args)
throw new NullPointerException(); //example, throw a runtime exception
}
};
new Thread(new ApplicationLoader(), appStarter).start();
}
//We overload this method from our parent
//ThreadGroup , which will make sure that it
//gets called when it needs to be. This is
//where the magic occurs.
public void uncaughtException(Thread thread, Throwable exception)
{
//Handle the error/exception.
//Typical operations might be displaying a
//useful dialog, writing to an event log, etc.
exception.printStackTrace();//example, print stack trace
}
}
呵呵,uncaughtException好像是唯一能够处理线程抛出的uncaught异常的入口。看来还是有细心人啊。确实如此,通过ThreadGroup的uncaughtException方法还是有处理的机会。当线程抛出uncaughtException的时候,JVM会调用ThreadGroup的此方法。默认的处理如下:
<<
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
e.printStackTrace(System.err);
}
}
>>
每个Thread都会有一个ThreadGroup对象,可以通过Thread.getThreadGroup()方法得到,提供了上述默认的uncaught异常处理方法。
上面没有提这点,因为俺认为在正常的情况下,这个方法的处理情况就已经足够了。还是那个线程设计的理念:“线程的问题应该线程自己本身来解决,而不要委托到外部。”通常情况下,外部不需要处理线程的异常。当然也有例外。:)
posted on 2009-08-07 12:38 Frank_Fang 阅读(5851) 评论(1) 编辑 收藏 所属分类: Java编程