#920 – A finally Block Is Not Executed When a Corrupted State Exception Occurs

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

920-001

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

4 Responses to #920 – A finally Block Is Not Executed When a Corrupted State Exception Occurs

  1. Joxin says:

    Hi Sean,

    This is an informative article.. Thank you for sharing all the info about c#

    Googling gave me another couple of exceptions that do not reach finally block are -:

    StackOverflowException
    ExecutingEngineException

    Thanks again ,
    Joxin

  2. vincpa says:

    There is another way to bypass the finally block

    void Main()
    {
    var enumerator = GetStuff().GetEnumerator();

    enumerator.MoveNext();

    Console.WriteLine (enumerator.Current);
    }

    IEnumerable GetStuff() {

    try {

    yield return 1;
    yield return 2;

    } finally {
    Console.WriteLine (“Will never be called”);
    }
    }

    // Prints 1

  3. Anony says:

    You forgot to add HandleProcessCorruptedStateExceptionsAttribute to CausesAccessViolation() method.

    Each methods have to have HandleProcessCorruptedStateExceptionsAttribute to handle AccessViolation.

  4. Pingback: c# – Gracefully handling corrupted state exceptions – in c# | Mister bricole !

Leave a comment