I'm working on a method that does something given a string parameter. A valid value for the string parameter is anything other than null or string.Empty. So my code looks like this.
private void SomeMethod(string someArgument) { if(string.IsNullOrEmpty(someArgument)) throw new ArgumentNullException("someArgument"); // do some work }
Nothing too exciting there. My question is, is it okay to throw an ArgumentNullException even if the string is equal to string.Empty? Because technically it isn't null. If you believe it should not throw ArgumentNullException, what exception should be thrown?
The ArgumentNullException is thrown when a null value is passed to a method that does not accept null values as valid input. They're provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null.
To prevent the error, instantiate the object. An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null . To prevent the error, check for a return value that is null and call the second method only if the return value is not null .
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.
The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.
ArgumentException should be thrown for the String.Empty
case. This would indicate an issue other than it being null. To avoid a NullReferenceException
I check for null first, then I trim and check for the empty case to prevent any whitespace from passing.
private void SomeMethod(string someArgument) { if(someArgument == null) throw new ArgumentNullException("someArgument"); if (someArgument.Trim() == String.Empty) throw new ArgumentException("Input cannot be empty", "someArgument"); // do some work }
As of .NET 4.0 you can use the String.IsNullOrWhiteSpace
method to perform these checks in one go. By doing so you forgo the ability to specify a granular exception type, so I would opt for the ArgumentException
and update the message accordingly.
You should throw an ArgumentException
if an empty string is not an accepted input for your method. It may be very confusing to clients if you throw an ArgumentNullException
while they didn't provide a null
argument.
It is simply another use case. You may also have methods that do not accept null input values but that do accept empty strings. It's important to be consistent across your entire application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With