I am looking for a BCL exception type to throw in case of unexpected return value from a call to another method.
I would name it somehow like UnexpectedReturnValueException, but obviously .NET Framework does not have anything like this.
Here is an example of code to illustrate:
public class SomeClass
{
private int savedMonth;
private ISomeOtherClass other;
public void DoSomething(int month, string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
if (!value.StartsWith("A"))
{
throw new ArgumentException("Value should always start with an 'A'", "value");
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", "Month should be in range of 1 to 12");
}
if (savedMonth == month)
{
throw new InvalidOperationException("Provided month should be different from saved month");
}
var result = other.GetResult();
if (result == null)
{
throw new ??? // What should I throw here?
}
// do other work here
}
}
public interface ISomeOtherClass
{
SomeOtherClassReturnValue GetResult();
}
public class SomeOtherClassReturnValue
{
}
Important:
As per my understanding based on MSDN the following exceptions are not suitable here:
ArgumentException- The exception that is thrown when one of the arguments provided to a method is not valid.ArgumentNullException- The exception that is thrown when a null reference is passed to a method that does not accept it as a valid argument.ArgumentOutOfRangeException- The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.InvalidOperationException- The exception that is thrown when a method call is invalid for the object's current state.
other.GetResult()is written in such a way that it can return null, how is that unexpected?SomeClassis just usingother, it can provide its expectation in form of thrown exception. As an example, let's suppose theotheris a Guid generator returning astring. In this case we have all rights to expect the value not to be null. And we express it in code by checking the return value and throwingUnexpectedResultExceptionrather than gettingNullReferenceExceptionwhen using this value orArgumentNullExceptionwhen trying to add it to dictionary, for example.