3

Possible Duplicate:
In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown ?

Will finally be executed in this scenario (in C#)?

try
{
    // Do something.
}
catch
{
    // Rethrow the exception.
    throw;
}
finally
{
    // Will this part be executed?
}
Community
  • 1
  • 1
niaher
  • 9,460
  • 7
  • 67
  • 86
  • See this duplicate (or one of the other duplicates linked there): http://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try-catch-finally-if-an-unhandled – Dirk Vollmar May 23 '09 at 08:55

3 Answers3

11

Yes, finally is always executed.

A simple example for demonstrating the behaviour:

private void Button_Click(object sender, EventArgs e)
{
    try
    {
        ThrowingMethod();
    }
    catch
    { 
    }
}

private void ThrowingMethod()
{
    try
    {
        throw new InvalidOperationException("some exception");
    }
    catch
    {
        throw;
    }
    finally
    {
        MessageBox.Show("finally");
    }
}
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
3

(Edit: Clarifications from comments incorporated - thanks guys)
Finally is always executed. The only exceptions I know of are;

  • You pull the power plug
  • If a thread that is running as "background" is terminated because the main program to which it belongs is ending, the finally block in that thread will not be executed. See Joseph Albahari.
  • Other async exceptions like stackoverflows and out-of-memory. See this question.

Most of the scenarios where Finally is not executed has to do with catastrohic failure, with the exception of the background thread one, so it is worth being aware of that one in particular.

Community
  • 1
  • 1
flytzen
  • 7,348
  • 5
  • 38
  • 54
1

Yes.

And you can easily test this out.

But the very fact that you ask the question is a good argument for writing this as a try/catch block nested inside a try/finally. Much easier on the eyes.

H H
  • 263,252
  • 30
  • 330
  • 514