-2

I have this block of code:

try{
    this.connection.Open();
    cmd.ExecuteScalar();
    return true;
}
catch(Exception exc){
    throw exc;
}
finally{
    this.connection.Close();
}

I know that if the catch throws the exception, the finally block will run anyways.

But what about the return in the try?

If the try block returns true, will the finally block close my connection?

Is this safe?

Phiter
  • 14,570
  • 14
  • 50
  • 84

2 Answers2

5

Yes, it does. It is safe to work as you do now.

It executes the finally after you exit the code block, no matter if that is caused by a return or not.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
5

MSDN states

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

So, yes.

Sadique
  • 22,572
  • 7
  • 65
  • 91