Why should I always make my Exceptions [serializable]? (.NET)

前端 未结 4 1985
再見小時候
再見小時候 2020-11-27 04:58

Referring to What is the correct way to make a custom .NET Exception serializable?
and Are all .NET Exceptions serializable? ...

Why should my exceptio

相关标签:
4条回答
  • 2020-11-27 05:27

    Another place where objects required to be serializable is Asp.Net Session. We store last exception in Session and not serializable exceptions needs extra translation to store their details as serializable( specifying original exception as inner doesn't help)

    0 讨论(0)
  • 2020-11-27 05:33

    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.


    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.

    0 讨论(0)
  • 2020-11-27 05:43

    In addition to Talljoe's answer, your exceptions may be passed across Web Services as well, in this case the exception needs to be serializable/deserializable so it can be turned into XML and transmitted by the Web Service

    0 讨论(0)
  • 2020-11-27 05:43

    I think that the default for all classes should be Serializable unless they contain a class that is explicitly not serializable. It's annoying to not be able to transfer a class just because some designer didn't think about it.

    The same thing with "Final", all variables should be "Final" by default unless you specifically say that they are "Mutable".

    Also, I'm not sure it makes sense to have a variable that is not private.

    Oh well, need to design my own language.

    But the answer is, you don't know how your exception will be used and they are assumed to be able to be thrown across remote calls.

    0 讨论(0)
提交回复
热议问题