缺少数据的例外 [英] Exception for missing data

查看:93
本文介绍了缺少数据的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道丢失数据应该抛出什么样的异常。例如,如果xml节点不包含数据。 引发新的异常(...)会很容易,但是不建议这样做。另一个选择是创建一个新的异常类,例如 MissingDataException InvalidDataException ,但是这种情况下没有内置的异常类吗?

I was wondering what kind of exception should one throw for missing data. For example if an xml node doesn't contain data. It would be easy to "throw new Exception(...)" but this is not recommended. Another option would be to create a new exception class like MissingDataException or InvalidDataException but isn't there a built-in exception class for this case?

推荐答案

作为经验法则,请在派生自己的.NET Framework异常之前,先查找合适的异常以引发适当的异常。要直接回答您的问题,目前没有可抛出的丢失数据异常,但这并不意味着没有适合您的情况的异常。

As a rule of thumb, check the existing .NET framework exceptions for a suitable exception to throw before deriving your own. To answer your question directly, there is no "missing data" exception currently available to throw, but that doesn't mean there aren't suitable exceptions to cover your situation.

在您的情况下,不起眼的 InvalidOperationException 可能合适;当您在对象上调用方法时,会引发此异常,但对象的状态不适用于该操作。这样的示例包括在封闭流上调用方法以及已通过集合末尾的枚举器。如果XML数据是对象的内部状态,并且方法调用已发现错误的数据,请 InvalidOperationException 是不错的选择。

In your case, the humble InvalidOperationException may be suitable; this exception is thrown when you call a method on an object, but the object's state is not appropriate for the operation. Examples of this include calling methods on a closed stream and an enumerator that has passed the end of the collection. If the XML data is the internal state of an object, and a method call has discovered the bad data, InvalidOperationException is a good candidate.

如果要将XML数据传递给方法,则 ArgumentException 或其一种派生方式可能是合适的选择。这些异常中有一小部分,所有这些异常都表明传递给方法的参数与预期的方法不同。

If you are passing your XML data to a method, an ArgumentException, or one of its derivatives may be an appropriate choice. There is a small family of these exceptions, all indicating that an argument passed to a method is not as the method expected.

您只想在以下情况下创建自定义异常您希望对异常情况的处理与其他例外情况有所不同。如果确实选择创建自己的异常,请确保从比 Exception ,因此基类隐含了异常的性质。

You will only want to create a custom exception when you want the exceptional circumstance to be handled differently from other exceptions. If you do choose to create your own exception, be sure to derive it from a higher exception than Exception, so that the nature of the exception is implied by the base class.

这篇关于缺少数据的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆