2012-04-27 69 views
4

我正在使用一個庫創建自己的線程,並引發異常。我怎樣才能捕捉到這個異常?拋出異常下面標註一行:如何捕獲Java中另一個線程拋出的異常?

ResourceDescriptor rd = new ResourceDescriptor(); 
     rd.setWsType(ResourceDescriptor.TYPE_FOLDER); 
     fullUri += "/" + token; 
     System.out.println(fullUri); 
     // >>> EXCEPTION THROWN ON THE FOLLOWING LINE <<< 
     rd.setUriString(fullUri.replaceAll("_", "")); 
     try{ 
      rd = server.getWSClient().get(rd, null); 
     }catch(Exception e){ 
      if(e.getMessage().contains("resource was not found")){ 
       this.addFolder(fullUri, label, false); 
       System.out.println("Folder does not exist, will be added now."); 
      }else{ 
       System.out.println("Error Messages: " + e.getMessage()); 
      } 
     } 
+1

你如何調用拋出豁免的方法? (可能是:如何知道異常拋出?) – DerMike 2012-04-27 14:19:12

+0

我已經嘗試捕獲泛型異常類,但我仍然得到異常拋出。我GOOGLE了它,似乎是從我正在使用的庫中的另一個線程拋出。該庫通過Web服務與Web應用程序進行交互。 – yuejdesigner85 2012-04-27 15:01:19

回答

5

如果你已經是一個Thread對象那麼有沒有辦法趕上任何異常(我假設是RuntimeException)。執行此操作的正確方法是使用ExecutorService使用的Future<?>類,但您無法控制我假設的開始Thread的代碼。

如果您提供Runnable或者如果您要將任何代碼注入庫中,那麼您可以將它封裝到一個類中,以便爲您捕獲並保存Exception,但只有當代碼中存在異常或者從您調用的代碼中拋出。像下面這樣:

final AtomicReference<Exception> exception = new AtomicReference<Exception>(); 
Thread thread = library.someMethod(new Runnable() { 
    public void run() { 
     try { 
     // call a bunch of code that might throw 
     } catch (Exception e) { 
     // store our exception thrown by the inner thread 
     exception.set(e); 
     } 
    } 
}); 
// we assume the library starts the thread 
// wait for the thread to finish somehow, maybe call library.join() 
thread.join(); 
if (exception.get() != null) { 
    throw exception.get(); 
} 

而且,@Ortwin提到,如果你是分叉自己的線程也可以設置未捕獲的異常處理程序:

thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { 
    public void uncaughtException(Thread t, Throwable e) { 
     // log it, dump it to the console, or ... 
    } 
}); 

但是,如果內部的線程代碼圖書館不能被你包裝,那麼這是行不通的。如果您編輯問題並顯示一些代碼並提供更多詳細信息,我可以編輯我的問題以提供更好的幫助。

+0

如果你提供了一個'Thread'而不是'Runnable',你可以重載'join'方法。這將允許您檢查線程是否退出異常,並在連接線程的上下文中重新拋出異常。 – ccurtsinger 2012-04-27 14:12:59

+0

@ccurtsinger'加入'是最後的 – artbristol 2012-04-27 14:15:38

+0

@artbristol你​​是對的。那真不幸。 – ccurtsinger 2012-04-27 14:20:20

16

如果你不能抓住它或許可以幫助你:

如果你有Thread對象,你可以嘗試設置UncaughtExceptionHandler。 看看Thread.setUncaughtExceptionHandler(...)

給我們一些關於您使用的庫以及如何使用它的更多細節。

+3

+1我不知道這件事。這比我的答案要好。 – Gray 2012-04-27 17:23:09

+0

我沒有任何控制由我使用的庫創建的線程,所以我不能明確地在其線程上設置未捕獲的異常處理程序。我該怎麼辦? – yuejdesigner85 2012-05-03 14:36:53

+0

看看[這裏](http://stackoverflow.com/questions/1323408/get-a-list-of-all-threads-currently-running-in-java)。這樣你就可以控制'Thread'對象;)它當然不是一個乾淨的解決方案,但值得一試。 – 2012-05-03 16:58:38

相關問題