Throwing ArgumentNullException

前端 未结 12 2180
名媛妹妹
名媛妹妹 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:22

    I'd prefer the parameter check with the explicit ArgumentNullException, too.

    Looking at the metadata:

     //
        // Summary:
        //     Initializes a new instance of the System.ArgumentNullException class with
        //     the name of the parameter that causes this exception.
        //
        // Parameters:
        //   paramName:
        //     The name of the parameter that caused the exception.
        public ArgumentNullException(string paramName);
    

    You can see, that the string should be the name of the parameter, that is null, and so give the developer a hint on what is going wrong.

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

    If you program defensively you should fail fast. So check your inputs and error out at the beginning of your code. You should be nice to your caller and give them the most descriptive error message you can.

    0 讨论(0)
  • 2020-12-08 02:26
    1. Do it explicitly if you do not want a Null value. Otherwise, when someone else look at your code, they will think that passing a Null value is acceptable.

    2. Do it as early as you can. This way, you do not propagate the "wrong" behavior of having a Null when it's not supposed to.

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

    I agree with the idea of failing fast - however it is wise to know why failing fast is practical. Consider this example:

    void someMethod(SomeClass x)
    {       
        x.Property.doSomething();
    }
    

    If you rely on the NullReferenceException to tell you that something was wrong, how will you know what was null? The stack trace will only give you a line number, not which reference was null. In this example x or x.Property could both have been null and without failing fast with aggressive checking beforehand, you will not know which it is.

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

    No excuse not to make the check these days. C# has moved on and you can do this very neatly using a discard and a null coalescing operator:

    _ = declaringType ?? throw new ArgumentNullException(nameof(declaringType));
    _ = methodname ?? throw new ArgumentNullException(nameof(methodName));
    
    0 讨论(0)
  • 2020-12-08 02:32

    I prefer the explicit exception, for these reasons:

    • If the method has more than one SomeClass argument it gives you the opportunity to say which one it is (everything else is available in the call stack).
    • What if you do something that may have a side effect before referencing x?
    0 讨论(0)
提交回复
热议问题