使用ThreadGroup來處理異常

 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方法中處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章