0

對於一個項目,我一直在工作,我們有一些塊看起來像這樣的:用更具體的異常類型替換泛型異常?

A類:

try { 
    callSomeMethod(); 
} 
catch (Exception e) { 
    throw new SomeCustomExceptionTypeForMetrics(""); 
} 

然而,我與更換,我們趕上與一般例外的所有實例任務只有特定的「預期」類型的例外。

問題是callSomeMethod()有這樣的事情

B類:

try { 
    if (someCondition...) { 

    } 
    else { 
     //failed 
     throw new RuntimeException("Timeout while waiting for results") 
    } 
} 
catch(InterruptedException e) { 
    // do some failure stuff here 
    throw new RuntimeException("Something here"); 
} 

理想的情況下,我集團一直叫我改變,因爲越好,我不能改變callSomeMethod()的簽名,但他們也不希望只捕獲A類中的任何RuntimeException,因爲他們不想僅捕獲任何類型的RuntimeException - 僅限於B類除外。

處理此問題的最佳方法是什麼?

+2

將這些「RuntimeExeption」更改爲更具體的內容。根據需要創建自定義類。 –

+0

我理解這是否正確:你應該捕獲RuntimeExceptions,但只有當他們明確地被拋出到Java代碼中的類B中,拋出新的RuntimeException(),而忽略可能來自其他地方的那些呢? –

+0

正在修改B類選項嗎? – slambeth

回答

0

假設你callSomeMethod的簽名包含throws Exception,你不能改變它:在方法更改RuntimeException s到自定義Exception類,然後在A類:

try { 
    callSomeMethod(); 
} 
catch (Exception e) { 
    if(e instanceof CustomException) 
     //Log it or something, for metrics? 
} 

這是有點傻,但如果你不能改變方法簽名可能是必要的。 (如果你可以改變它,你可以直接抓住CustomException。)你甚至可以在你的記錄器中製作一個方法,它會檢查它是什麼類型,並相應地執行。然後在每個需要編輯的catch語句中使用這個方法。

在設計此解決方案時,請記住RuntimeException不需要被捕獲。它可以爲您節省一些麻煩。

0

如果chnage在B類代碼如下

try { 
     if (someCondition...) { 

     } 
     else { 
      //failed 
      throw new MyRuntimeException("Timeout while waiting for results") 
     } 
    } 
    catch(InterruptedException e) { 
     // do some failure stuff here 
     throw new MyRuntimeException("Something here"); 
    } 

,並定義爲MyRuntimeException:

class MyRuntimeException extends RuntimeException{ 
.. 
} 

在A類,你只需要捕捉MyRuntimeException例外。

希望能解決您的問題!