Throwing ArgumentNullException

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

提交回复
热议问题