Throwing ArgumentNullException

前端 未结 12 2179
名媛妹妹
名媛妹妹 2020-12-08 02:10

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it\'s a fatal error and an exception shoul

相关标签:
12条回答
  • 2020-12-08 02:12

    I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.

    If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.

    If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.

    0 讨论(0)
  • 2020-12-08 02:14

    You should explicitly throw an ArgumentNullException if you are expecting the input to not be null. You might want to write a class called Guard that provides helper methods for this. So your code will be:

    void someMethod(SomeClass x, SomeClass y)
    {
        Guard.NotNull(x,"x","someMethod received a null x argument!");
        Guard.NotNull(y,"y","someMethod received a null y argument!");
    
    
        x.doSomething();
        y.doSomething();
    }
    

    The NonNull method would do the nullity check and throw a NullArgumentException with the error message specified in the call.

    0 讨论(0)
  • 2020-12-08 02:15

    I'll probably be downvoted for this, but I think completely different.

    What about following a good practice called "never pass null" and remove the ugly exception checking?

    If the parameter is an object, DO NOT PASS NULL. Also, DO NOT RETURN NULL. You can even use the Null object pattern to help with that.

    If it's optional, use default values (if your language supports them) or create an overload.

    Much cleaner than ugly exceptions.

    0 讨论(0)
  • 2020-12-08 02:16

    You can use syntax like the following to not just throw an ArgumentNullException but have that exception name the parameter as part of its error text as well. E.g.;

    void SomeMethod(SomeObject someObject)
    {
        Throw.IfArgNull(() => someObject);
        //... do more stuff
    }
    

    The class used to raise the exception is;

    public static class Throw
    {
        public static void IfArgNull<T>(Expression<Func<T>> arg)
        {
            if (arg == null)
            {
                throw new ArgumentNullException(nameof(arg), "There is no expression with which to test the object's value.");
            }
    
            // get the variable name of the argument
            MemberExpression metaData = arg.Body as MemberExpression;
            if (metaData == null)
            {
                throw new ArgumentException("Unable to retrieve the name of the object being tested.", nameof(arg));
            }
    
            // can the data type be null at all
            string argName = metaData.Member.Name;
            Type type = typeof(T);
            if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
            {
                throw new ArgumentException("The expression does not specify a nullible type.", argName);
            }
    
            // get the value and check for null
            if (arg.Compile()() == null)
            {
                throw new ArgumentNullException(argName);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-08 02:17

    I always follow the practice of fail fast. If your method is dependent on X and you understand X might be passed in null, null check it and raise the exception immediately instead of prolonging the point of failure.

    2016 update:

    Real world example. I strongly recommend the usage of JetBrains Annotations.

    [Pure]
    public static object Call([NotNull] Type declaringType, 
                              [NotNull] string methodName, 
                              [CanBeNull] object instance)
    {
        if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));
        if (methodName == null) throw new ArgumentNullException(nameof(methodName));
    

    Guard statements have been vastly improved with C# 6 providing the nameof operator.

    0 讨论(0)
  • 2020-12-08 02:17

    It is better to throw the ArgumentNullException sooner rather than later. If you throw it, you can provide more helpful information on the problem than a NullReferenceException.

    0 讨论(0)
提交回复
热议问题