Consider the following class and method:
public class MyDto
{
public MyDtoChild Child {get; set;}
}
and
public void ProcessDto(MyDto myDto)
{
if(myDto == null) throw new ArgumentNullException("myDto");
this.CheckSomething(myDto.Child.ChildProperty);
}
If called with a MyDto
with a null Child
left to it's own devices this will throw a NullReferenceException
which can be extremely difficult to diagnose in more complex methods.
Typically I throw an ArgumentNullException
at the start of the method if myDto
is null but what is the appropriate exception to throw if myDto.Children
is null? An ArgumentNullException
? A NullReferenceException
? A custom exception?
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null. Otherwise it is a matter of preference. It certainly shouldn't be a matter of preference.
null can be cast to anything*, including an Exception. Just as you could return null if your method signature specifies you should return an Exception (or indeed a string, or Person class), you can throw it.
We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
As mentioned by the previous answers, it should not be an ArgumentNullException
since the argument myDTO
is not NULL.
To me it makes more sense to throw an ArgumentException
since the argument passed to the method did not meet the requirements (you expect Children to not be null). Moreover, your situation fits the ArgumentException's description:
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method.
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