CLR 4.0: Corrupted State Exceptions

Corrupted state exceptions are designed to help you have fewer bugs in your code by making it harder to make common mistakes around exception handling.

A very common pattern is code like this:

public void FileSave(String name) { try { FileStream fs = new FileStream(name, FileMode.Create); } catch (Exception e) { MessageBox.Show("File Open Error"); throw new Exception(IOException); }

The standard recommendation is not to catch System.Exception but rather catch the more specific exceptions (in this case, IOException).

While this is a somewhat contrived example, what would happen if Exception were really an AccessViolationException or some other exception indicating that the process state has been corrupted? What you really want to do is get out fast before persistent data is corrupted or more work is lost.

To help solve this problem and minimize the chance that you will catch exceptions like this, CLR 4.0 introduces Corrupted State Exceptions, which cannot be caught by normal catch statements.

There are still places where you do want to catch these types of exceptions, particularly in your application’s “main” function or when you are loading add-ins.  There are also rare circumstances when you know code that throws an exception isn’t dangerous, such as when calling native code.

In order to support these scenarios, a new HandleProcessCorruptedStateExceptions attribute has been added. This attribute is added to the function that catches these exceptions. There is also a process wide compatibility switch named legacyCorruptedStateExceptionsPolicy which when set to true will cause the code to operate under the older exception handling behavior.

](http://digg.com/submit?url=http%3a%2f%2fgeekswithblogs.net%2fsdorman%2farchive%2f2008%2f11%2f07%2fclr-4.0-corrupting-state-exceptions.aspx&title=CLR+4.0%3a+Corrupting+State+Exceptions)

This article is part of the GWB Archives. Original Author: Scott Dorman

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.