捕获线程中的异常

来源:互联网 发布:矩阵的二范数性质 编辑:程序博客网 时间:2024/05/20 11:46

一、捕获线程中的异常

public class CatchThreadException extends ThreadGroup {private CatchThreadException() {super("ApplicationLoader");}// 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.System.out.println("CatchThreadException[ThreadGroup] uncaughtException execute");System.out.println("Catch " + thread + " exception: " + exception.getMessage());}public static void main(String[] args) {Runnable appStarter = new Runnable() {public void run() {// invoke your applicationSystem.out.println("appStarter run..");if (true) {throw new RuntimeException("test appStarter throw runtimeException");}}};new Thread(new CatchThreadException(), appStarter).start();}}

二、注意不要捕获error的异常
error 和exception区别
http://blog.csdn.net/duoshanx/article/details/84485
他们都继承自Throwable
对Error的子集的快速了解可以让你知道许多类的名字,如VirtualMachineError、ThreadDeath和LinkageError。在你打算截获这些错误时,确信你要处理它们,因为它们是严重的问题,所以是错误。
Error是Throwable的一个子集,它指的是一个合理的应用程序不能截获的严重的问题。大多数都是反常的情况。


0 0