If I return out of a try/finally block in C# does the code in the finally always run?

zorg picture zorg · Apr 21, 2012 · Viewed 21.3k times · Source

It seems like it does as per some initial testing, but what I'd like to know is if it is guaranteed to return or if in some cases it can not return? This is critical for my application but I haven't found a use-case yet where it wouldn't return.
I'd like to get expertise on the subject.

Answer

Eric Lippert picture Eric Lippert · Apr 21, 2012

There are a number of inaccuracies in the other answers.

Control is passed to the finally block when control leaves the try block normally -- that is, by a return, goto, break, continue, or simply falling off the end. Control is passed to the finally block when control leaves the try block via an exception that has been caught by an enclosing catch block.

In every other circumstance there is no guarantee that the code in the finally block will be called. In particular:

  • If the try block code goes into an infinite loop, or the thread is frozen and never unfrozen, then the finally block code is never called.

  • If the process is paused in the debugger and then aggressively killed then the finally block is never called. If the process does a fail-fast then the finally block is never called.

  • If the power cord is pulled out of the wall then the finally block is never called.

  • If there is an exception thrown without a corresponding catch block then whether the finally block runs or not is an implementation detail of the runtime. The runtime can choose any behaviour when there is an uncaught exception. Both "do not run the finally blocks" and "do run the finally blocks" are examples of "any behaviour", so either can be chosen. Typically what the runtime does is ask the user if they want to attach a debugger before the finally blocks run; if the user says no then the finally blocks run. But again: the runtime is not required to do that. It could just fail fast.

You cannot rely on finally blocks always being called. If you require a strong guarantee about code executing then you should not be writing a try-finally, you should be writing a constrained execution region. Writing a CER correctly is one of the most difficult tasks in C# programming, so study the documentation carefully before you try to write the code.

Incidentally, a "fun fact" about finally-blocked gotos is:

try { goto X; } finally { throw y; } 
X : Console.WriteLine("X");

X is an unreachable label targetted by a reachable goto! So next time you're at a party you can be like "hey everybody, can anyone make a C# program that has an unreachable label that is targetted by a reachable goto?" and you'll see who at the party has read the reachability specification and who has not!