#917 – Corrupted State Exceptions Are Not Normally Caught

Starting with .NET 4.0, there are a class of exceptions that will not be caught within a general catch block that catches all exceptions deriving from System.Exception.  By default, a corrupted state exception will not be caught as a System.Exception.  A corrupted state exception is a type of exception, like an access violation, that likely results in the internal state of the process being corrupt.

In the example below, we artificially generate an access violation.  Note that the exception that is raised is not caught, but treated as an unhandled exception.  (Our catch block never executes).

        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);
        }

917-001

Advertisement

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

2 Responses to #917 – Corrupted State Exceptions Are Not Normally Caught

  1. Pingback: #918 – Catching Corrupted State Exceptions | 2,000 Things You Should Know About C#

  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: