gpt4 book ai didi

c# - 将返回值错误报告提升为异常

转载 作者:行者123 更新时间:2023-12-03 08:35:30 25 4
gpt4 key购买 nike

在《框架设计指南》一书中有一章是关于异常的,他们谈论基于返回值的错误报告和基于异常的错误报告,以及我们在使用像C#这样的OO语言时应该避免基于返回值的错误报告和使用这一事实。异常(exception)。考虑到这一点,我正在查看我们的代码,这些代码是八年前用Visual Basic编写的,去年使用自动工具将其转换为C#!

所以这是我正在查看的一种方法,我想知道那本书中的建议是否适用于这种方法,如果可以,那么重写该方法的更好方法是什么?

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;
}

最佳答案

尽可能抛出特定的异常。然后,在这种情况下,您不需要返回值

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
  • 关于c# - 将返回值错误报告提升为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10248153/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com