#918 – Catching Corrupted State Exceptions

Corrupted State Exceptions are exceptions that indicate that the memory state of the current process is likely corrupt.  These CSEs by default cannot be caught by your code.  This is normally what you want, since you typically don’t want to continue execution when one of these exceptions occurs.

You can, however, set an attribute on a method indicating that you do want to catch Corrupted State Exceptions.  If you set the HandleProcessCorruptedStateExceptions attribute on a method, it will then be able to catch this category of exceptions.

In the example below, we are able to catch the access violation exception.

        [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()
        {
            IntPtr ptr = new IntPtr(123);
            Marshal.StructureToPtr(123, ptr, true);
        }

918-001