c# - 来自另一个方法的意外返回值的异常

标签 c# .net exception

我正在寻找一个 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 适合这种情况。

SomeClassISomeOtherClass 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/

相关文章:

c# - 如何检查是否脏,但保存时不检查?

c# - UInt16数组,C#中的后缀是什么?

c# - 浏览器成功但 HttpWebRequest 失败(超时)

exception - 非详尽模式的更好异常(exception),以防万一

python - python 中的 Thrift TTransportException

c# - 如何在解决方案级别使用 Microsoft.Net.Compilers?

c# - 原子列表-此集合线程安全且快速吗?

c# - Gmail 错误 :The SMTP server requires a secure connection or the client was not authenticated. 服务器响应为 : 5. 5.1 需要身份验证

c# - Parallel.ForEach/多线程的最佳使用

c++ - 在 C++ 中哪些操作不能抛出异常?