views:

1619

answers:

9

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
  }
}
+38  A: 

Simple answer: Yes.

Andrew Rollings
+39  A: 

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 (ThreadAbortException, OutOfMemoryException, StackOverflowException).

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

Mehrdad Afshari
Yes, StackOverflow is always the exception... :)
dalle
+1 For mentioning exceptions.
Andrew Hare
+1  A: 

Yes. That is in fact that main point of a finally statement. Unless something catestrophic occurs (out of memory, computer unplugged, etc.) the finally statement should always be executed.

Jeffrey L Whitledge
+23  A: 

Not to be rude, but whenever I have something like, "how does the framework handle X?", I just make a little sample console app and try it out. Especially when it's something simple like this. You could basically paste your code above into a .cs file, compile it in the VS command line, and have your answer in a matter of seconds.

Jacob Adams
Although that's exactly what I would have done, I do see the value in having a resource like SO where we can share the results of these tests to prevent others from having to repeat them.
Jon B
To be honest, I normally would do a simple console app like this; however, I'm not at a computer that has a C# compiler on it. If I was looking at the code on a Windows box at the moment I would be creating one. Right now, SO's faster than me driving to another location for such a test.
JamesEggers
He could have gotten his answer from trying it out, but how confident could he be that his result wasn't just a coincidence? Maybe the type of exception is important. Maybe some other context is a factor.
Rob Kennedy
Asking on SO is faster than testing for a simple question like this, and answers found here can give you additional, useful information. Though I agree that testing things by yourself is a good habit to have.
Meta-Knight
+5  A: 

Quoting from MSDN

finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

Perpetualcoder
A: 

In response to Perpetualcoder - normally the finally is guaranteed to fire, but as has been noted above, there are certain cases where this won't apply. For instance, if you have a StackOverflowException, the application comes to a sudden halt - so the finally block never gets called.

Bottom line - MSDN does not always equal truth.

Pete OHanlon
A: 

Nitpicking is my life.;-> Well, that and snarkiness.

Pete OHanlon
this and tghe other should be in comments - we're trying to produce something useful, remember!
Ruben Bartelink
Agreed, I deleted my response (and I just noticed that Jeffrey touched on that topic before me - silly default by-Votes sorting.) However, my post was only partially tongue-in-cheek. People tend to rely on finally and forget external conditions. Also, jeez, lighten up, a bit of humor never hurts...
Mihai Limbășan
Just making the point that comments is where relevant banter and discussion can go. The actual responses are sorted by votes so that the relevant stuff is easiest to find (and so peopple dont have to vote stuff to <0 :D). BTW the podcast is well worth a listen (if you have lots of time!)
Ruben Bartelink
+9  A: 

Here's a little test:

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("before");
        Console.WriteLine(test());
        Console.WriteLine("after");
    }

    static string test()
    {
        try
        {
            return "return";
        }
        finally
        {
            Console.WriteLine("finally");
        }
    }
}

The result is:

before

finally

return

after

Jon B
A: 

Good one Mehrdad, thanx !!!!

--Anish Sneh

Anish Sneh