为什么我应该总是使我的异常 [serializable]?(.网) [英] Why should I always make my Exceptions [serializable]? (.NET)

查看:28
本文介绍了为什么我应该总是使我的异常 [serializable]?(.网)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考 使自定义 .NET 异常可序列化的正确方法是什么?
所有 .NET 异常都可序列化吗? ...

为什么我的异常应该是可序列化的?
有人说,如果第三方库定义的自定义异常不可序列化,则可以认为是错误".为什么?

Why should my exceptions be serializable?
Someone said "it can be considered a bug" if a custom exception defined by a third party library, is not serializable. Why?

为什么在这方面异常与其他类不同?

Why are exceptions different than other classes in this regard?

推荐答案

因为您的异常可能需要在不同的 AppDomain 之间进行编组,如果它们不能(正确)序列化,您将丢失宝贵的调试信息.与其他类不同,您无法控制您的异常是否会被编组——它会.

Because your exceptions may need to be marshalled between different AppDomains and if they aren't (properly) serializable you will lose precious debugging information. Unlike other classes, you won't have control over whether your exception will be marshalled -- it will.

当我的意思是您将无法控制"时,我的意思是您创建的类通常具有有限的存在空间,并且这种存在是众所周知的.如果它是一个返回值并且有人试图在不同的 AppDomain(或在不同的机器上)调用它,他们会得到一个错误并且只能说不要那样使用它".调用者知道他们必须将其转换为可以序列化的类型(通过包装方法调用).然而,由于异常如果没有被发现就会上升到最顶端,它们可以超越您甚至不知道自己拥有的 AppDomain 边界.您在不同 AppDomain 中深度 20 级的自定义应用程序异常可能是 Main() 报告的异常,并且在此过程中没有任何内容可以为您将其转换为可序列化的异常.

When I mean "you won't have control" I mean that classes you create generally have a finite space of existence and the existence is well known. If it's a return value and someone tries to call it in a different AppDomain (or on a different machine) they will get a fault and can just say "Don't use it that way." The caller knows they have to convert it into a type that can be serialized (by wrapping the method call). However since exceptions are bubbled up to the very top if not caught they can transcend AppDomain boundaries you didn't even know you had. Your custom application exception 20 levels deep in a different AppDomain might be the exception reported at Main() and nothing along the way is going to convert it into a serializable exception for you.

这篇关于为什么我应该总是使我的异常 [serializable]?(.网)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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