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
{
}
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.If null value is exceptional and therefore exception is needed, best built-in type is InvalidOperationException
.
As author states, error is not caused directly from method parameters, therefore no any Argument* -Exception is suitable for this case.
SomeClass
has ISomeOtherClass other
as a private member in the class and method caller cannot have any visibility to it. ISomeOtherClass
-dependency is then part of object's internal state. As documentation states:
InvalidOperationException is thrown when a method call is invalid for the object's current state.
InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.
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