public static void Main() { try { // This code forces a division by 0 and catches the // resulting exception. try { int zero = 0; int ecks = 1 / zero; } catch (Exception ex) { // Create a new exception to throw. NewException newExcept = new NewException("Divided by", 0); // This FileStream is used for the serialization. FileStream fs = new FileStream("NewException.dat", FileMode.Create); try { // Serialize the exception. BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, newExcept); // Rewind the stream and deserialize the exception. fs.Position = 0; NewException deserExcept = (NewException)formatter.Deserialize(fs); Console.WriteLine( "Forced a division by 0, caught the resulting exception, \n" + "and created a derived exception with custom data. \n" + "Serialized the exception and deserialized it:\n"); Console.WriteLine("StringData: {0}", deserExcept.StringData); Console.WriteLine("intData: {0}", deserExcept.IntData); } catch (SerializationException se) { Console.WriteLine("Failed to serialize: {0}", se.ToString()); } finally { fs.Close(); Console.ReadLine(); } } } catch (NewException ex) { Console.WriteLine("StringData: {0}", ex.StringData); Console.WriteLine("IntData: {0}", ex.IntData); } }
//<snippet2> // This method is called when deserialization of the // exception is complete. void ISafeSerializationData.CompleteDeserialization (object obj) { // Since the exception simply contains an instance of // the exception state object, we can repopulate it // here by just setting its instance field to be equal // to this deserialized state instance. NewException exception = obj as NewException; exception.m_state = this; }