BinaryFormatter.Deserialize rewraps some exceptions in SerializationException

The BinaryFormatter.Deserialize method now rewraps some exception objects inside a SerializationException before propagating the exception back to the caller.

Change description

Previously, the BinaryFormatter.Deserialize method allowed some arbitrary exceptions, such as ArgumentNullException, to propagate up the stack to its callers.

In .NET 5 and later, the BinaryFormatter.Deserialize method more aggressively catches exceptions that occur due to invalid deserialization operations and wraps them in a SerializationException.

Version introduced

5.0

In most cases, you don't need to take any action. However, if your call site depends on a particular exception being thrown, you can unwrap the exception from the outer SerializationException, as shown in the following example.

Stream inputStream = GetInputStream();
var formatter = new BinaryFormatter();

try
{
    object deserialized = formatter.Deserialize(inputStream);
}
catch (MyException myEx)
{
    // Handle 'myEx' here in case it was thrown directly.
}
catch (SerializationException serEx) when (serEx.InnerException is MyException myEx)
{
    // Handle 'myEx' here in case it was wrapped in SerializationException.
}

Affected APIs