tags:

views:

402

answers:

4

Can all .NET exception objects be serialized?

Summary of responses:

  1. They should be, but historically, there have been exceptions.
  2. Objects in the Data dictionary may prevent the exception from serializing.
+2  A: 

System.Exception implements ISerializable and it is the base class for all exceptions, so yes.

See: http://msdn.microsoft.com/en-us/library/system.exception.aspx

Matt Briggs
Except that derived classes do not inherit the SerializableAttribute, so each derived class must also be decorated in order for that class to be serialzable.
GalacticCowboy
+7  A: 

Yes, but historically there have been (no pun intended) exceptions.

In other words, all Exceptions SHOULD be serializable, but some custom Exceptions from third party code may not be, depending on how they're implemented.

For example, in the .NET 1.0 era, exceptions from the official Microsoft Oracle database provider were not serializable, due to bugs in their code.

Jeff Atwood
+4  A: 

System.Exception implements ISerializable, but descendants might not deserialize if they don't implement the correct overloaded constructor with signature (SerializationInfo,StreamingContext).

Barry Kelly
+8  A: 

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.IsSerialable (not a 100% solid check).
  • The property is virtual. A derived exception type could override and use a Hashtable which does 0 checking.
JaredPar