Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Null Exception to throw?

Tags:

c#

exception

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?

like image 759
Liath Avatar asked Jul 09 '14 07:07

Liath


People also ask

Should I return null or throw 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.

Can you throw a null exception?

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.

Which exception we can throw?

We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.


1 Answers

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.

like image 144
Vincent Avatar answered Nov 06 '22 12:11

Vincent