ArgumentException vs. ArgumentNullException?

前端 未结 4 1066
予麋鹿
予麋鹿 2021-01-03 20:13

I’m refactoring some code and adding a method which will replace a (soon-to-be) deprecated method. The new method has the following signature:

FooResult Foo         


        
相关标签:
4条回答
  • 2021-01-03 20:51

    In this case, it may be best to check for a null reference of the FooArgs parameter inside that method, and throw an ArgumentNullException if a null reference has been passed in. Then if other methods or sections of code use the parameters contained within the args class, they should be the ones to check this and throw exceptions as necessary. However, if your method that takes in the args class is the one to use all the arguments, then it would be better to check for valid parameters in that method, as you suggested.

    Also, use ArgumentNullException only for arguments that are null references. If it's simply an invalid value (for example an empty string), then you should use the more generic ArgumentException.

    0 讨论(0)
  • 2021-01-03 20:54

    This kind of depends on your tooling and how you feel about your tooling (resharper, fxcops and the like). Some static code analysis tools accept this:

    throw new ArgumentNullException(“args.Property...”,"args");
    

    and reject this

    throw new ArgumentNullException(“args.Property...”,"args.Property");
    

    So if you want to use the tooling, then assertions of null-hood against a parameter property must throw an ArgumentException

    It's also valid to just make it up as you go along. What ever communicates the right message to the maintenance developer to help him pass the parameters correctly is the correct message.

    0 讨论(0)
  • 2021-01-03 21:09

    You need to add a check for the args itself to be non-null. The ANE is not appropriate for individual components, so you need to use more general AE, like this:

    if (args == null)
        throw new ArgumentNullException(“args”);
    if (args.Property1 == null)
        throw new ArgumentException(“Property1 cannot be null.”, “args”);
    if (args.Property... == null)
        throw new ArgumentException(“Property... cannot be null.”, “args”);
    if (args.PropertyN == null)
        throw new ArgumentException(“Property2 cannot be null.”, “args”);
    
    0 讨论(0)
  • 2021-01-03 21:12

    While I agree completely with dasblinkenlight's answer, you may also want to consider moving the validation for FooArgs into the FooArgs class itself. If this class is designed specifically to move arguments around, it is likely not valid for it to have null proeprties, in which case, I would allow it's constructor to do it's validation.

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