2017-07-28 88 views
0

如何使用jmh來測試引發異常的方法?如何測試引發異常的方法?

我試圖在江鈴控股有限公司1.19以下:

@Benchmark 
public void throwException() throws IllegalArgumentException 
{ 
    throw new IllegalArgumentException("Hard-coded exception"); 
} 

,但得到這個錯誤:

# Run progress: 0.00% complete, ETA 00:02:00 
# Fork: 1 of 3 
# Warmup Iteration 1: <failure> 

java.lang.IllegalArgumentException: Hard-coded exception 
[...] 

我應該按如下黑洞異常?

@Benchmark 
public void throwException(Blackhole bh) 
{ 
    try 
    { 
     throw new IllegalArgumentException("Hard-coded exception"); 
    } 
    catch (IllegalArgumentException e) 
    { 
     bh.consume(e); 
    } 
} 

還是有另一種方法告訴jmh接受拋出的異常?

+1

閱讀此https://shipilev.net/blog/2014/exceptional-performance/並檢查此https://github.com/shipilev/article-exception-benchmarks/tree/master/src/main/java/淨/ shipilev/perf /例外 –

+0

@OlegEstekhin好吧,但它爲什麼工作?什麼讓他的代碼拋出異常,而我的觸發失敗? – Gili

+0

我認爲主要區別在於該示例調用拋出異常的方法,而不是從基準本身拋出 –

回答

0

總結從我從Kiril S.Oleg Estekhin收到我已經收到了答案:如果基準方法拋出異常

江鈴控股有限公司將始終失敗。爲了糾正這種情況,基準測試方法必須抓住這個例外。然後,它可以使用Blackhole對象消耗該異常,或者從基準測試方法返回該異常。這將阻止編譯器優化掉throw語句。

相關問題