System.Exception.Data属性 [英] System.Exception.Data Property

查看:126
本文介绍了System.Exception.Data属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Exception类(实际上是任何异常)都具有几乎总是为空的Data属性。在抛出异常的时候,应该有什么用吗?还是有一些我不知道的内部使用?

The System.Exception class (actually any exception) has Data property which is almost always empty. While throwing exceptions, should this field be of any use? Or does it have some internal use that I am not aware of?

推荐答案

文档似乎足够清楚它的用法(加重点):

The documentation seems clear enough as to its use (emphasis added):


获取一组密钥/值对,提供有关异常的其他用户定义信息

为什么它首先存在?我认为这是同样的原因控制有一个 标签属性。在.NET的早期(在每个Bob和Betty程序员都理解对象和继承之前),他们希望让API变得简单,每个人都可以找出如何添加额外的数据。

Why does it exist in the first place? I assume it's the same reason Control has a Tag property. In the early days of .NET (before every Bob and Betty programmer understood objects and inheritance) they wanted to make the API simple enough that everyone could figure out how to add extra data to things.

但是,创建从 System.Exception 派生的自定义异常的点不一定包括其他信息,而是使客户端有可能限制他们只能抓住他们可以处理的例外。如果他们知道如何处理您的代码可以抛出的一组定义的异常,那么他们应该只能捕获这些异常,而无需捕获基础 System.Exception class。你绝对不应该 要求客户端代码捕获非特定的异常类并读取一个属性来确定它是什么类型的异常(因此它们是否能够处理它) )。

However, the point of creating custom exceptions that derive from System.Exception is not necessarily to include additional information, but to make it possible for the client to limit the exceptions they catch to only those that they can handle. If they know how to handle a set of defined exceptions that your code can throw, they should be able to only catch those exceptions, without having to catch the base System.Exception class. What you should definitely never do is require the client code to catch a non-specific exception class and read a property to determine what type of exception it is (and thus whether or not they are able to handle it).

我以前从来没有使用过此属性。我不得不检查文件,甚至看到它确实存在。但我认为这是最有用的实现自定义异常日志记录。您可以将很多重要信息嵌入到 Data 属性中(无论异常类的派生级别如何),然后将其传递给您的记录代码。反射器表明它在几个地方内部用于精确的目的。这也很好,您提供的所有信息都会自动正确序列化。

I've honestly never used this property before. I had to check the documentation to even see that it did indeed exist. But I imagine it's most useful for implementing custom exception logging. You can embed a lot of important information into the Data property (regardless of the level of derivation of exception class), and then pass that off to your logging code. Reflector indicates that it's used internally in a handful of places for precisely that purpose. It's also nice that all the information you provide here gets correctly serialized for you automatically.

这篇关于System.Exception.Data属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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