#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.

        static void Main(string[] args)
                Console.WriteLine("Before call to CausesAccessViolation()");
                Console.WriteLine("Before call to CausesAccessViolation()");
            catch (Exception exc)
                Console.WriteLine(string.Format("Hey, I caught an Exception: {0}", exc.ToString()));


        static void CausesAccessViolation()
                IntPtr ptr = new IntPtr(123);
                Marshal.StructureToPtr(123, ptr, true);
                Console.WriteLine("* finally block in CausesAccessViolation() executing");



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 -:


    Thanks again ,

  2. vincpa says:

    There is another way to bypass the finally block

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


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

Facebook photo

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

Connecting to %s

%d bloggers like this: