Jeffrey Richter: On exception handling and state management

9780735627048f Jeffrey here. In the third edition of my CLR via C# book (Microsoft Press, 2010; 896 pages), I rewrote the “Exception Handling” chapter. In fact, I even changed the title of this chapter to “Exceptions and State Management” to reflect that a large part of having an exception-handling strategy is really all about handling errors while still ensuring that none of your application’s state is corrupt after the error occurs. This is very important, of course, because an application accessing corrupted state causes the amount of corrupted state to increase, resulting in bugs and security holes. So, a good approach to take in your application is to allow any unexpected exceptions to terminate your application. Windows automatically destroys all state used by a terminating application, and this is good because it prevents any corrupted state from being persisted in a file or database. Within your code, this means not swallowing exceptions in your application code so that the exception becomes unhandled, allowing Windows to kill your process.

My chapter also explains why it is futile to think that you can build applications in .NET that are reliable and robust against all possible failures. If you need extreme reliability and robustness against failures and state corruption, native code is the way to go and you can also use managed code but store your data in a native data store (such as SQL Server). But I’d also like to point out that many applications do not need complete reliability, which is why the programmer productivity provided by the .NET Framework is so heavily valued over making a truly reliable application. In my book, I also explain how you can use the CLR’s Constrained Execution Regions (CERs) to prevent CLR exceptions (FileLoadException, BadImageFormatException, InvalidProgramException, FieldAccessException, MethodAccessException, MissingFieldException, MissingMethodException, and more) from occurring at indeterminate times, which basically makes it impossible for CLR-related facilities to corrupt your application’s state. And I also explain how to use the new .NET Code Contract feature, which allows methods to declaratively state their preconditions, ensuring that the method doesn’t manipulate state via invalid arguments passed to the method.

Understanding exception handling and its relationship to state management is critically important for building reliable, bug-free, and security-conscious applications and components. This topic has many aspects related to it, including the mechanics of exception handling, how to define your own exceptions, how to throw exceptions, guidelines and best practices, unhandled exceptions and integration with the debugger and Windows Error Reporting, and performance. My book covers all of these subjects and more in great detail.