Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception for unexpected return value from another method

Tags:

c#

.net

exception

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.
like image 258
Alexander Yezutov Avatar asked May 05 '14 00:05

Alexander Yezutov


1 Answers

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.

like image 194
Risto M Avatar answered Sep 28 '22 05:09

Risto M