我正在寻找一个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
{
}
Run Code Online (Sandbox Code Playgroud)
根据我对MSDN的理解,以下例外情况不适用于此:
ArgumentException- 提供给方法的其中一个参数无效时引发的异常.ArgumentNullException- 将空引用传递给不接受它作为有效参数的方法时引发的异常.ArgumentOutOfRangeException- 当参数的值超出被调用方法定义的允许值范围时引发的异常.InvalidOperationException- 方法调用对于对象的当前状态无效时引发的异常.如果 null 值是异常的,因此需要异常,则最好的内置类型是InvalidOperationException。
正如作者所说,错误不是直接由方法参数引起的,因此没有任何 Argument* -Exception 适合这种情况。
SomeClass作为ISomeOtherClass other类中的私有成员,方法调用者不能对其有任何可见性。ISomeOtherClass- 依赖性是对象内部状态的一部分。正如文档所述:
当方法调用对于对象的当前状态无效时,将引发 InvalidOperationException。
InvalidOperationException 用于因参数无效以外的原因导致调用方法失败的情况。
| 归档时间: |
|
| 查看次数: |
984 次 |
| 最近记录: |