Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all .NET exceptions serializable?

Tags:

c#

.net

exception

Can all .NET exception objects be serialized?

like image 606
Esteban Araya Avatar asked Dec 05 '08 00:12

Esteban Araya


People also ask

Do exceptions need to be serializable?

Exceptions should be serializable so that they can automatically be marshalled across application domains or threads. At a minimum, you should mark your custom exception as serializable and implement the four basic constructors shown below. (This example shows a custom exception type that has no custom data).

What is serialization exception?

SerializationException(String, Exception) Initializes a new instance of the SerializationException class with a specified error message and a reference to the inner exception that is the cause of this exception.

What is .NET serialization?

.Net Serialization (C#/VB.Net) Serialization can be defined as the process of converting the state of an object instance to a stream of data, so that it can be transported across the network or can be persisted in the storage location.

Is serializable inherited C#?

You must explicitly mark each derived class as [Serializable] . If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.


1 Answers

Yes and no. As Jeff and others have pointed out, the all exception classes should and almost always are serializable. If you run across a particular exception class that is not serializable, it is quite possibly a bug.

But when considering serializability you need to consider both the immediate class and all types which are members of this type (this is a recursive process). The base Exception class has a Data property which is of type IDictionary. This is problematic because it allows you, or anyone else, to add any object into the Exception. If this object is not serializable then serialization of the Exception will fail.

The default implementation of the Data property does do some basic checking to ensure an object being added is serializable. But it is flawed in several ways

  • Only does top level checking for serializability of a type and this check is only done by checking Type.IsSerializable (not a 100% solid check). 
  • The property is virtual. A derived exception type could override and use a Hashtable which does 0 checking.
like image 135
JaredPar Avatar answered Sep 21 '22 03:09

JaredPar