53

For a constructor with a single parameter, is it OK to throw an ArgumentNullException inside the constructor if the parameter is null/empty? OR, should it be thrown in the method that actually uses the argument? Thanks.

4 Answers 4

56

Yes, if it is completely essential then throw the exception. You should not* throw the exception later.

Always remember the "Fail Early Principle". Concept being fail now, so you don't waste time debugging or experience unexpected system functionality.

Alternatively you could also throw a ArgumentException for "" and ArgumentNullException for null. In either case make sure you throw a valid Exception message.


Always a good reference article for managing exceptions: Good Exception Management Rules of Thumb


Side note on what @Steve Michelotti said (because i am a huge fan of CodeContracts)

Contract.Requires<ArgumentNullException>(inputParemeter!= null, "inputparameter cannot be null");
Contract.Requires<ArgumentException>(inputParemeter!= "", "inputparameter cannot be empty string");

alternatively

Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter), "inputparameter cannot be null or empty string");
2
  • 5
    Another good rule is "fail early." Especially for processing parameters and arguments, fail at the earliest opportunity to detect the error, or as close as possible to the point in space-time when the error occurs.
    – Cylon Cat
    Sep 2, 2010 at 18:12
  • You are right! I was struggling to find "name" of the right principle.
    – Nix
    Sep 2, 2010 at 18:13
17

Throwing it in the constructor is fine - there are several classes in the .NET framework that do this. Additionally, check out code contracts for this.

0
4

From what it sounds like, you pass in a parameter into the constructor to be held by the class for use in some other method later on. If you're not actually using the argument in the constructor, you should probably think about moving the argument to be a parameter of the method that's actually using it.

2
  • 1
    I would if I could, but it's part of a series of tasks being executed based on an interface, so, I can't modify the method signatures. Sep 2, 2010 at 18:08
  • In that case, I agree with everyone else that failing in the constructor is definitely the best option. Sep 2, 2010 at 18:12
1

I'd put the check in the property that you set when the constructor is called... That way the exception would be thrown in all cases.

2
  • There's no indication that a property is being set by the constructor.
    – Jon Skeet
    Sep 2, 2010 at 18:10
  • Yes but would it be caught? Class actions are normally encased in try blocks not class creation.
    – Canacourse
    Apr 24, 2012 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.