2017-07-12 21 views
1

通常在運行Future並等待結果時,我只能捕獲InterruptedException | ExecutionException如何捕捉期貨的自定義例外?

但是如果任務拋出一個CustomException,我想明確地捕獲它呢?我能做比檢查e.getCause() instanceof CustomException更好嗎?

List<Future> futures; //run some task 

for (Future future : futures) { 
    try { 
     future.get(); //may throw CustomException 
    } catch (InterruptedException | ExecutionException e) { 
     if (e.getCause() instanceof CustomException) { 
      //how to catch directly? 
     } 
    } 
} 

回答

3

假設CustomException被選中,這是不可能的,因爲語言不允許添加catch對於這樣的例外是不是Future#get()簽名的一部分,因此不能用這種方法拋出(這是它合同的一部分)。在你的代碼中,評論may throw CustomException是否因爲你知道執行這個Future特定的任務。就Future接口的get方法而言,任何此類實現特定的異常將被封裝爲ExecutionException的原因。

此外,使用e.getCause()檢查這樣一個自定義異常爲ExecutionException在文件中明確提到的正確方法:

異常試圖檢索中止通過投擲任務的結果時,拋出一個例外。這種異常可以使用getCause()方法進行檢查。

-1

您可以根據需要捕捉儘可能多的異常,但應該按照特定的順序捕捉異常,其中更嚴格的異常必須在子類異常之後進行。

例如:

catch (CustomException e) { 

} catch (InterruptedException | ExecutionException e) { 

} 

// It could be even there if CustomException is not extended from InterruptedException | ExecutionException 
+0

不,'的Future.get()'只能扔掉那些兩種例外明確。不再。 – membersound