2014-10-10 74 views
4

有什麼改變縮小catch塊的類型是否有性能影響?

try { 
    canThrowDifferentExceptions(); 
} catch (Exception e) { 
    // handle exception 
} 

try { 
    canThrowDifferentExceptions(); 
} catch (Exception1 | Exception2 | Exception3 e) { 
    // handle exception 
} 

我看到過於寬泛的catch塊,創建隱瞞不打算爲異常的風險的表現內涵,但我很好奇多抓的表現特徵。

+0

性能問題?這是一個例外,意外情況(主要)。你能解釋一下,在哪種情況下,這可能會成爲任何計劃的瓶頸? – ControlAltDel 2014-10-10 17:01:46

+0

這絕對是實現特定的。 – Qix 2014-10-10 17:02:22

+0

我對優化_specific_程序不感興趣,我試圖調查縮小捕獲的異常類型是否合理,作爲_universal_最佳實踐。我也很樂意獲得特定於實現的響應。 – 2014-10-10 17:02:43

回答

1

唯一的區別在於,在多捕獲點指向僅一條線而另一條指向正確捕獲線的情況下的異常表。

唯一的不同是goto在non multi catch的末尾。

如果是單個catch(Exception e),表格異常只包含一行,要求進行擴展轉換,不會引入開銷。

總體而言,根據一個的成本goto,您不應該期望任何性能差異


測試代碼:

public static void main(final String[] args) { 
    int i = 0; 
    try { 
     if (i == 1) { 
      throw new NullPointerException(); 
     } else if (i == 2) { 
      throw new ArrayIndexOutOfBoundsException(); 
     } else { 
      throw new IllegalStateException(); 
     } 
    } catch (NullPointerException | ArrayIndexOutOfBoundsException 
      | IllegalStateException e) { 
    } 
} 

與非多抓的區別是:

32c32,36 
<  37: return   
--- 
>  37: goto   45 
>  40: astore_2  
>  41: goto   45 
>  44: astore_2  
>  45: return   
//  Exception table: 
//  from to target type 
//   2 36 36 Class java/lang/NullPointerException 
36,37c40,41 
<   2 36 36 Class java/lang/ArrayIndexOutOfBoundsException 
<   2 36 36 Class java/lang/IllegalStateException 
--- 
>   2 36 40 Class java/lang/ArrayIndexOutOfBoundsException 
>   2 36 44 Class java/lang/IllegalStateException 

catch(Exception e)

//  Exception table: 
//  from to target type 
<   2 36 36 Class java/lang/NullPointerException 
<   2 36 36 Class java/lang/ArrayIndexOutOfBoundsException 
<   2 36 36 Class java/lang/IllegalStateException 
--- 
>   2 36 36 Class java/lang/Exception 
+0

這看起來像是單獨的catch塊到單個multi-catch塊的區別,但是我也很感興趣,如果以前只有一個catch(Exception e)塊。 – 2014-10-10 17:35:21

+0

編輯添加比較 – 2014-10-10 18:11:30