2012-04-20 131 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

有(至少)在异常处理尽可能多的意见,也有编码,但良好经验法则是,在特殊情况下应该抛出异常。

那么,更新失败是一种特殊情况吗?