【问题标题】:Exception for unexpected return value from another method来自另一个方法的意外返回值异常
【发布时间】: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 的以下链接上阅读更多相关信息

标签: c# .net exception


【解决方案1】:

如果空值是异常,因此需要异常,最好的内置类型是InvalidOperationException

正如作者所说,错误不是直接由方法参数引起的,因此没有任何 Argument* -Exception 适合这种情况。

SomeClass 具有 ISomeOtherClass other 作为类中的私有成员,方法调用者无法看到它。 ISomeOtherClass-dependency 是对象内部状态的一部分。正如documentation 所说:

当方法调用无效时抛出 InvalidOperationException 对象的当前状态。

InvalidOperationException 用于调用失败的情况 方法是由无效参数以外的原因引起的。

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2017-02-12
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多