BinaryFormatter.Deserialize 重新包装 SerializationException 中的一些异常
现在,BinaryFormatter.Deserialize 方法在将异常传播回调用方之前,会重新包装 SerializationException 中的某些异常对象。
更改描述
以前,BinaryFormatter.Deserialize 方法允许一些任意异常(如 ArgumentNullException)将堆栈向上传播到其调用方。
在 .NET 5 及更高版本中,BinaryFormatter.Deserialize 方法更主动地捕获由于反序列化操作无效而发生的异常,并将它们包装在 SerializationException 中。
引入的版本
5.0
建议操作
在大多数情况下,你不必执行任何操作。 但是,如果你的调用站点依赖于引发的特定异常,则可以从外部 SerializationException 中解包异常,如下面的示例中所示。
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.
}
受影响的 API
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈