2012-04-20 88 views
0

在框架設計指南書中有關於Exception的章節,他們討論基於返回值的錯誤報告和基於異常的錯誤報告,以及我們在像C#這樣的OO語言中應該避免基於返回值的錯誤報告並使用異常。考慮到這一點,我正在研究八年前用Visual Basic編寫的代碼,去年一款自動工具被轉換爲C#!uplifitng返回值錯誤報告異常

所以這裏是我正在看的一種方法,我想知道這本書的建議是否適用於這種方法,如果是的話,那麼重寫這種方法會是更好的方法嗎?

public int Update(CaseStep oCaseStepIn) 
{ 
    int result = 0; 
    //Update the master object with the passed in object 

    result = UCommonIndep.gnUPDATE_FAILED; 
    if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED) 
    { 
     return result; 
    } 

    CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey); 
    if (oCaseStep == null) 
    { 
     return result; 
    } 

    return result; 
} 

回答

1

如果可能,拋出特定異常。然後,在這種情況下,您不需要返回值

public void Update(CaseStep oCaseStepIn) 
{ 
    //Update the master object with the passed in object 
    if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED) 
     throw new ValidationFailedUpdateException(); 

    CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey); 
    if (oCaseStep == null) 
     throw new KeyObjectNotFoundUpdateException(); 

    if (oCaseStep.Update(oCaseStepIn) != UCommonIndep.gnUPDATE_SUCCESSFUL) 
     throw new UpdateFailedException(); 

    //******************************* 
    //FYI - Insert code here to update any Key values that might have changed. 
} 
  • UpdateFailedException延伸異常
  • ValidationFailedUpdateException延伸UpdateFailedException
  • KeyObjectNotFoundUpdateException延伸UpdateFailedException
0

有(至少)在異常處理儘可能多的意見,也有編碼,但良好經驗法則是,在特殊情況下應該拋出異常。

那麼,更新失敗是一種特殊情況嗎?