我正在寻找一个 BCL 异常类型以在调用另一个方法时出现意外返回值时抛出。
我会以某种方式将其命名为 UnexpectedReturnValueException
,但显然 .NET Framework 没有这样的东西。
下面是一个代码示例来说明:
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
{
}
重要:
根据我基于 MSDN 的理解,以下异常(exception)情况不适用于此处:
ArgumentException
- 当提供给方法的参数之一无效时抛出的异常。ArgumentNullException
- 当 null 引用传递给不接受它作为有效参数的方法时抛出的异常。ArgumentOutOfRangeException
- 当参数的值超出允许的值范围时抛出的异常由调用的方法定义。InvalidOperationException
- 当方法调用对于对象的当前状态无效时抛出的异常。
最佳答案
如果空值是exceptional,因此需要异常,最好的内置类型是InvalidOperationException
。
正如作者所说,错误不是直接由方法参数引起的,因此没有任何 Argument* -Exception 适合这种情况。
SomeClass
将 ISomeOtherClass other
作为类中的私有(private)成员,方法调用者无法看到它。 ISomeOtherClass
- 依赖是对象内部状态的一部分。作为documentation状态:
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.
关于c# - 来自另一个方法的意外返回值的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23463330/