public class Dog
{
public string Name { get; set;}
}
Then in this scenario null is passed to FeedDog()
public void FeedDog(Dog dog)
{
Console.WriteLine("Feeding "+dog.Name); // throws NullReferenceException
}
How can I do this so that it throws DogDoesNotExistException without doing this
public void FeedDog(Dog dog)
{
if (dog == null)
throw new DogDoesNotExistException(); // want to get rid of this
Console.WriteLine("Feeding "+dog.Name);
}
So when you do this
public void FeedDog(Dog dog)
{
Console.WriteLine("Feeding "+dog.Name); // throws DogDoesNotExistException
}
GetDogshould throw the exception.NullReferenceExceptionshould be transformed intoDogDoesNotExistExceptionin this class. This is very error prone. You need to be explicit. Do you really need to throw the exception ? If the reason is for the exception to bubble up and be handled on a different layer then OK, but why no just return a boolean using the TryXXX pattern ?