Friday, July 9, 2010

Try And Catch Me

There was a fun question posted to StackOverflow today basically asking if the "finally" block in a try/catch will always execute.  The responses varied from a definite "yes" to a definite "no" with lots of discussions and mutual corrections made by the crowd.  So I thought it would be fun to enumerate here the things which can cause a "finally" block to not be executed in a .NET application.  This may not be an exhaustive list, so please add/correct as you see fit...

  1. StackOverFlowException - The process has run out of necessary resources, it simply can't execute any more code.  Even if the next line of code is to pass control to the "finally" block, it can't get there.
  2. OutOfMemoryException - See above.
  3. ExecutingEngineException - It's rare, I've never seen this one.  Basically, the .NET runtime b0rked, the application can't continue.
  4. Environment.FailFast() - Kills the application with extreme prejudice, not allowing it to finish what it was doing.
  5. Process/Thread is killed by an external process/thread - The application isn't asked nicely to terminate, it's shot in the head by the OS.  Note that a ThreadAbortException will attempt to execute a "finally" block before aborting.  But there are more sinister ways to kill an enemy process.
  6. Infinite loop within the try block - The application will run indefinitely until #5 above happens.
  7. Power failure.
In this I've learned a few things, which are good things to know.  First, I didn't know about Environment.FailFast().  I don't know if I'll ever use it, but it's good to know that it's there.  Also, more importantly, I'd never heard of Constrained Execution Regions before.  In writing enterprise software with high reliability requirements, this is definitely something I should look into.

It's just good to keep in mind that a "finally" block is not the end of the discussion when talking about reliable code.

1 comment:

  1. Pretty cool stuff, and thanks for the reminder that Finally blocks are not guaranteed.

    ReplyDelete