【发布时间】:2014-06-21 05:09:51
【问题描述】:
我正在寻找一种 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 的理解,以下例外在这里不适用:
-
ArgumentException- 当提供给方法的参数之一无效时引发的异常。 -
ArgumentNullException- 当空引用传递给不接受它作为有效参数的方法时引发的异常。 -
ArgumentOutOfRangeException- 当参数的值超出调用方法定义的允许值范围时引发的异常。 -
InvalidOperationException- 当方法调用对于对象的当前状态无效时引发的异常。
【问题讨论】:
-
如果
other.GetResult()被写成可以返回null,这有什么意外? -
显然,这种情况不足以保证内置异常类型。您可以创建自己的异常类型并抛出它。
-
@Szymon,到目前为止
SomeClass只是使用other,它可以以抛出异常的形式提供它的期望。例如,假设other是一个返回string的Guid 生成器。在这种情况下,我们有权期望该值不为空。我们通过检查返回值并在代码中表达它并抛出UnexpectedResultException,而不是在使用这个值时得到NullReferenceException,或者在尝试将它添加到字典时得到ArgumentNullException。 -
@500-InternalServerError,这是正确的,我自己的异常类型始终是一个选项。但是我只是有一种感觉,应该有一些东西被认为是这种情况下的“最佳实践”:)
-
If other.GetResult();预计将返回空值作为正常行为,您应该在程序的自然流程中处理它,而不是使用异常。这也适用于您的输入测试。我建议使用 bool / string 返回值而不是抛出异常。您可以在 MSDN msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx 的以下链接上阅读更多相关信息