C# - Another “finally” trivia

If a function implementation has a try - catch block with a finally clause, then the finally code block is executed in all cases before exiting the function.

For example, in the following case:

int Foo()
{
     try
     {
          //do stuff here
          if(something_happened == true)
               return;
          //do something else
     }
     catch(Exception)
     {
     }
     finally
     {
          MessageBox.Show(”exiting method”)
     }
}

In the above function, even if the function exits at the first ‘if’ condition, the message will still be displayed.

Leave a Reply