#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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #918 – Catching Corrupted State Exceptions

  1. Pingback: Dew Drop – August 28, 2013 (#1,613) | Alvin Ashcraft's Morning Dew

  2. Pingback: #919 – Think Twice about Handling Corrupted State Exceptions | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: