#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 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

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: