#920 – A finally Block Is Not Executed When a Corrupted State Exception Occurs
August 30, 2013 4 Comments
When a corrupted state exception occurs as a result of executing some code within a try block, code within an associated finally block is not executed. This is true whether or not you use the HandleProcessCorruptedStateExceptions attribute to indicate that you want to catch corrupted state exceptions.
In the example below, we execute some code that causes an access violation and a corrupted state exception occurs. We do catch the CSE, but the code within our finally block is never executed.
[HandleProcessCorruptedStateExceptions] static void Main(string[] args) { try { Console.WriteLine("Before call to CausesAccessViolation()"); CausesAccessViolation(); Console.WriteLine("Before call to CausesAccessViolation()"); } catch (Exception exc) { Console.WriteLine(string.Format("Hey, I caught an Exception: {0}", exc.ToString())); } Console.ReadLine(); } static void CausesAccessViolation() { try { IntPtr ptr = new IntPtr(123); Marshal.StructureToPtr(123, ptr, true); } finally { Console.WriteLine("* finally block in CausesAccessViolation() executing"); } }