C# 检查方法参数时是否引发异常?

C# 检查方法参数时是否引发异常?,c#,exception,C#,Exception,在使用方法之前,我喜欢检查方法的所有参数是否具有正确的信息。大概是这样的: public method(MyType param1) { try { if(param1 == null) { throw new ArgumentNullException("Error1"); } if(param1.Property1 == null) { throw new ArgumentNullException(

在使用方法之前,我喜欢检查方法的所有参数是否具有正确的信息。大概是这样的:

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; }
}
public方法(MyType参数1)
{
尝试
{
if(param1==null)
{
抛出新的ArgumentNullException(“Error1”);
}
if(param1.Property1==null)
{
抛出新的ArgumentNullException(“Error2”);
}

if(param1.Property1.Amount当所需值为null或缺少时,您肯定应该抛出异常。我喜欢做的一件事是清除这种情况,即使用方法检查类型是否有效,并在代码可能抛出异常时使用异常注释

缺点是,如果使用正确,Validate(…)方法将被调用两次。我喜欢Validate(…)方法,因为它允许在引发异常之前进行更改以查找错误,因为任何类都可以调用Validate(…)

class-MyClass
{
/// 
///剂量
/// 
///无效操作例外
公共无效剂量测定(MyType MyType)
{
字符串错误消息;
如果(!验证(myType,out errorMessage))
抛出新的InvalidOperationException(string.Format(“参数myType无效:{0}”,errorMessage));
//完成
}
/// 
///有效
/// 
///无参数异常
公共静态bool验证(MyType MyType,out string errorMessage)
{
errorMessage=null;
if(myType==null)
抛出新的ArgumentNullException(“myType”);
if(string.IsNullOrEmpty(myType.Property1))
errorMessage=“需要属性1”;
if(string.IsNullOrEmpty(myType.Property2))
errorMessage=“需要属性2”;
返回errorMessage==null;
}
}
类MyType
{
公共字符串属性1{get;set;}
公共字符串属性2{get;set;}
}

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


不过,我肯定会去掉
try…catch
部分。它绝对是多余的,使代码变得比需要的更复杂(而且有点混乱)。

异常代价很高,但传递坏数据的代价更高。我不认为有问题(并鼓励)在这里抛出异常。毕竟,这不是一个紧密的循环,所以成本不是问题。您可以删除
try{}catch{throw;}
但是。是的,您应该为失败的前提条件抛出异常,尽管您不应该将整个方法包装在
try{}{catch throw;}
。对于第二种情况,我不会使用
ArgumentNullException
param1
的值在该点处不是空的,因此参数不是空的,即使它引用的对象的某些属性是空的。关键是“作为正常流”。如果某个内容是预期的,则不应抛出异常。如果某个内容不是预期的,则异常很好。因此,在有人调用方法的情况下,错误的异常是绝对可行的。因此,作为一个示例,如果正在分析的字符串可能为null,则不应抛出null参数异常。但是,如果字符串应该始终不为null,然后抛出该异常。
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; }
}