Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 236
Cheeso Avatar asked Jun 30 '09 23:06

Cheeso


People also ask

Why do exceptions need to be serializable?

All exceptions by default are serializable and that's a language design decision because the authors wanted exceptions to be capable of being sent across the wire without any special configuration.


2 Answers

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.

like image 191
Talljoe Avatar answered Sep 23 '22 19:09

Talljoe


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

like image 29
Jeffrey Cameron Avatar answered Sep 26 '22 19:09

Jeffrey Cameron