检查方法参数时是否抛出异常?



我喜欢在对它们做某事之前检查方法的所有参数是否具有正确的信息。像这样:

public method(MyType param1)
{
try
{
if(param1 == null)
{
throw new ArgumentNullException("Error1");
}
if(param1.Property1 == null)
{
throw new ArgumentNullException("Error2");
}
if(param1.Property1.Amount <= 0)
{
throw new ArgumentException("Error3");
}
...

//Do what I need with the parameter
}
catch { throw; }
}

但是,在这篇文章中,有人评论说,将异常作为正常流程抛出并不是一个好主意,但我不确定是否是这种情况,因为如果我必须检查参数并且还有像ArgumentNullExceptionArgumentException这样的异常,似乎可以在参数出现问题时抛出它, 这让我想知道这是否真的是一种糟糕的方式,我评论的例子。

另一个用户给出的另一个原因是异常消耗 4000-8000 个 CPU 周期。好吧,就我而言,目标是知道参数是否存在一些错误,并且如果应用程序按预期工作,则永远不会抛出异常,因此在实践中,如果应用程序没有错误,则性能不会降低。

因此,总而言之,我想知道在继续该过程之前如何处理参数检查的最佳方法。

谢谢。

当所需值为 null 或缺失时,您绝对应该抛出异常。为了清理这种情况,我喜欢做的一件事是使用一种方法来检查 Type 是否有效,并在我的代码可能引发异常时使用异常注释。

缺点是,如果使用得当,Validate(...( 方法会被调用两次。我喜欢 Validate(...( 方法,因为它允许在抛出异常之前进行更改以查找错误,因为任何类都可以调用 Validate(...

class MyClass
{
/// <summary>
/// DoSomething
/// </summary>
/// <exception cref="InvalidOperationException">InvalidOperationException</exception>
public void DoSomething(MyType myType)
{
string errorMessage;
if (!Validate(myType, out errorMessage))
throw new InvalidOperationException(string.Format("Argument myType is not valid: {0}", errorMessage));
// Finish
}
/// <summary>
/// IsValid
/// </summary>
/// <exception cref="ArgumentNullException">ArgumentNullException</exception>
public static bool Validate(MyType myType, out string errorMessage)
{
errorMessage = null;
if (myType == null)
throw new ArgumentNullException("myType");           
if (string.IsNullOrEmpty(myType.Property1))
errorMessage = "Property1 is required";
if (string.IsNullOrEmpty(myType.Property2))
errorMessage = "Property2 is required";
return errorMessage == null;
}
}
class MyType
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}

在参数验证后引发异常是一种好方法。通过这种方式,您可以显式地让使用您的方法的开发人员知道他调用不正确,这使他能够轻松修复此错误。

不过,我肯定会摆脱try...catch部分。它绝对是多余的,并且使代码比需要的更复杂(并且有点混乱(。

最新更新