Your exception handler can encounter an exception

Raymond Chen

Consider the following code,written in C# just for kicks; the problem is generic to anyenvironment that supports exception handling.

void ObliterateDocument()
{
 try {
  try {
   document.DestroyAll();
  } finally {
   document.Close();
   document.DestroyExtensions();
   document.DestroyPlugins();
  }
 } finally {
  document.Destroy();
 }
}

Some time later, you find yourself facing an assertionfailure from document.Destroy() claiming that you aredestroying the document while there are still active plugins.But there is your call to document.DestroyPlugins(),and it’s in a finally block, and the whole pointof a finally block is that there is no way you canescape without executing it.

So why didn’t document.DestroyPlugins() execute?

Because your exception handler itself encountered an exception.

The exception handler is not active during its ownfinally clause.As a result,if an exception is thrown during document.Close(),the exception handler search begins at the blockoutside the finally block.

(That the exception handler is not active during its ownfinally clause should be obvious. It would meanthat if an exception were to occur during the finallyclause, the program would go into an infinite loop. And it alsowouldn’t be possible to rethrow a caught exception; your throwwould end up caught by yourself!)

In this case, the exception was caught by some outer caller,causing the remainder of the first finallyblock to be abandoned. The other finally blocksdo run since they contain the one that died.

(This bug also exists in theproposed alternative to error-checking code posted byan anonymous commenter.)