Runnable appStarter = new Runnable() {
public void run() {
// invoke your application (i.e.MySystem.main(args)
throw new NullPointerException(); // example, throw a runtime
}
};
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
}
}[/code]以上代码就可以实现线程的异常捕捉。每个Thread都会有一个ThreadGroup对象,可以通过Thread.getThreadGroup()方法得到,此方法提供了上述默认的uncaught异常处理方法。
虽然可以处理,不过还是强调一点:线程的问题应该线程自己本身来解决,而不要委托到外部!