Let's say I have a method:
public void SayHello(User user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
Console.Write(string.Format("Hello from {0}", user.Name));
}
It's clear that I should use ArgumentNullException as it shown above to validate that user is not null. Now how can I validate that user.Name is not empty? Would it be a good practice to do like that:
if (string.IsNullOrWhiteSpace(user.Name))
throw new ArgumentNullException("user", "Username is empty");
No you shouldn't throw ArgumentNullException for this purpose as it is designed specifically to address null
references.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
Instead you should be using ArgumentException or your own subclass of it. let's say InvalidUserException
or something similar.
Even msdn talks about.
ArgumentNullException behaves identically to ArgumentException. It is provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null. For errors caused by arguments that are not null
So it is clear that if argument is null
use ArgumentNullException
and ArgumentException
otherwise.
That said, Ideally you shouldn't even allow someone to create an instance of User
with invalid username. I'd really design my User
class in such a way that it can never contain Name
as null
.
You should throw ArgumentException
if the argument is empty, ArgumentNullException
should only be used for null arguments:
if (string.IsNullOrWhiteSpace(user.Name))
throw new ArgumentException("Username is empty", "user");
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