@@ -89,22 +89,37 @@ internal static void Stash()
89
89
90
90
IFormatter formatter = CreateFormatter ( ) ;
91
91
var ms = new MemoryStream ( ) ;
92
- trace ( "serialization start" ) ;
93
- formatter . Serialize ( ms , runtimeStorage ) ;
94
- trace ( "serialization done" ) ;
95
-
96
- Debug . Assert ( ms . Length <= int . MaxValue ) ;
97
- byte [ ] data = ms . GetBuffer ( ) ;
98
- // TODO: use buffer api instead
99
- IntPtr mem = PyMem_Malloc ( ms . Length + IntPtr . Size ) ;
100
- Marshal . WriteIntPtr ( mem , ( IntPtr ) ms . Length ) ;
101
- Marshal . Copy ( data , 0 , mem + IntPtr . Size , ( int ) ms . Length ) ;
102
-
103
- ClearCLRData ( ) ;
104
- IntPtr capsule = PyCapsule_New ( mem , null , IntPtr . Zero ) ;
105
- PySys_SetObject ( "clr_data" , capsule ) ;
106
- // Let the dictionary own the reference
107
- XDecref ( capsule ) ;
92
+ IntPtr capsule = IntPtr . Zero ;
93
+ try
94
+ {
95
+ trace ( "serialization start" ) ;
96
+ formatter . Serialize ( ms , runtimeStorage ) ;
97
+ trace ( "serialization done" ) ;
98
+
99
+ Debug . Assert ( ms . Length <= int . MaxValue ) ;
100
+ byte [ ] data = ms . GetBuffer ( ) ;
101
+ // TODO: use buffer api instead
102
+ IntPtr mem = PyMem_Malloc ( ms . Length + IntPtr . Size ) ;
103
+ Marshal . WriteIntPtr ( mem , ( IntPtr ) ms . Length ) ;
104
+ Marshal . Copy ( data , 0 , mem + IntPtr . Size , ( int ) ms . Length ) ;
105
+
106
+ ClearCLRData ( ) ;
107
+ capsule = PyCapsule_New ( mem , null , IntPtr . Zero ) ;
108
+ PySys_SetObject ( "clr_data" , capsule ) ;
109
+
110
+ }
111
+ catch ( Exception e )
112
+ {
113
+ trace ( $ "Serialization failed! No runtime data will be saved. \n { e . Message } :: { e . StackTrace } ") ;
114
+ }
115
+ finally
116
+ {
117
+ if ( capsule != IntPtr . Zero )
118
+ {
119
+ // Let the dictionary own the reference
120
+ XDecref ( capsule ) ;
121
+ }
122
+ }
108
123
}
109
124
110
125
internal static void RestoreRuntimeData ( )
0 commit comments