BinaryFormatterを使用して、いくつかのオブジェクトをシリアル化および逆シリアル化します。これらのオブジェクトの構造は次のとおりです。
[Serializable()]
public class SerializableObject : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("SomeProperty", SomeProperty);
// similar for other properties
}
public SerializableObject(SerializationInfo info, StreamingContext context)
{
this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass));
// similar for other properties
}
}
オブジェクトを逆シリアル化しようとすると、「SomeProperty」エントリが見つからない場合(たとえば、名前が変更されたか削除されたため)、TargetInvocation例外がスローされることに気付きました。将来、SerializableObjectクラスのプロパティを変更する予定なので、次のようにアプリケーションをクラッシュさせるのではなく、例外をキャッチして問題のあるプロパティの値をデフォルト値に設定することを考えていました。
public SerializableObject(SerializationInfo info, StreamingContext context)
{
try
{
this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass));
}
catch (TargetInvocationException)
{
this.SomeProperty = SomePropertyClass.DefaultValue;
}
}
ご存知のように、処理方法がわからない、または処理できない例外をキャッチすることは悪い習慣なので、この場所でキャッチしても安全かどうかを尋ねています。他の理由(私にはわからないため、処理すべきではない)で同じ例外をスローできますか?