Patrice Calve

Life's short, have fun
posts - 53, comments - 77, trackbacks - 31

My Links

News

Archives

Post Categories

Image Galleries

Finally got the finally{} !

It took me a few years to get this Finally{}.

try
{
   DoA();  //known to throw an exception
}
catch(Exception ex)
{
   LogError(ex);
}

DoC();

Whether that DoC() is in a Finally or not, it would be called.  So I never could understand the use of that finally. 

Yesterday, I had it !  I asked my great friend Michel Prevost.  The finally{} exists to perform actions regardless of any “weird” actions in that catch{}.  And by “weird” I mean a “throw” or a “return“.

try
{
   DoA();  //known to throw an exception
}
catch(Exception ex)
{
   LogError(ex);
   throw new Exception("doh");
}
finally
{
  DoB();
}

DoB() will be executed, even though an error was thrown in the catch.  If a “return” was called instead of the throw new, DoB(); would have been called too.

It creates weird and unnatural flow of execution, but it makes the releasing of objects in an organized manner. 

I bet that if I look back at the documentation, everything will be evident !

I learn fast if get long explanations :)

Pat

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Thursday, October 06, 2005 9:57 AM |

Feedback

Gravatar

# re: Finally got the finally

Yep--also good when you are not catching all exception types (allowing some to bubble up to the calling procedure)

Sub DoStuff(Question)
Try
msgbox "Answer = " & GetAnswer(Question)
Catch ex as Exception
msgbox "Oops. " & ex.Description
End Try
End Sub

Function GetData(Question) as String
'Returns the Answer, or "Invalid Question"
Try
Conn.Open
'Retrieve Data
GetData = SQLComm.ExecuteScalar
Catch ex as SQLException
GetData = "Invalid Question"
'Other non-SQL exceptions bubble up and are handled differently
Finally
'Always close, no matter what
Conn.Close
End Try
End Function



End Function

10/6/2005 12:22 PM | BradC
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: