Will code in a Finally statement fire if I return a value in a Try block?


Question

I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block. Does the code in the Finally section still fire even though the rest of the try block doesn't?

Example:

public bool someMethod()
{
  try
  {
    return true;
    throw new Exception("test"); // doesn't seem to get executed
  }
  finally
  {
    //code in question
  }
}
1
221
4/16/2009 2:16:07 PM

Accepted Answer

Simple answer: Yes.

250
12/5/2008 8:50:47 PM

Normally, yes. The finally section is guaranteed to execute whatever happens including exceptions or return statement. An exception to this rule is an asynchronous exception happening on the thread (OutOfMemoryException, StackOverflowException).

To learn more about async exceptions and reliable code in that situations, read about constrained execution regions.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon