使用ThreadGroup来处理异常

来源:互联网 发布:网络女主播私下贩毒 编辑:程序博客网 时间:2024/05/17 01:42

 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)
    System.out.println("ssss");
//    throw new NullPointerException();
    
    throw new Error("sssdsds");

   }

  };

  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();

 }
}

 

这个是一个很好的异常处理机制。main中所有的错误都会转到uncaughtException方法中处理

原创粉丝点击