sub foo
try
call bar (which throws an exception)
catch
handle the exception <- only if exception thrown
finally
always do this
end try
do something else <- since exception handled, do this
end sub
the Finally block ALWAYS gets executed regardless of an exception being
thrown. Ok.
I submit that the second case is identical to the third case if I
rewrite number 2 as follows:
sub foo
try
call bar (which throws an exception)
catch
handle the exception <- only if exception thrown
end try
always do this
do something else <- since exception handled, do this
end sub
This begs the question - what is the use of Finally? I had assumed,
wrongly as it turns out, that in the event of an exception, Catch and
Finally would execute and control would return to the caller. If no
exception, Finally would execute and control continues to the next
statement.
I can see no use for Finally!
Sean
The finally always runs. After the finally, it's iffy. For example:
Dim conn As SqlConnection = New SqlConnection(...)
Dim ds As DataSet
Try
ds = GetDataFromDatabase(conn)
Catch ex As SqlException
' Log the error message or handle it some other way.
Return
Finally
' Perform cleanup, whether or not an exception was raised as well
' as whether or not we are exiting the function because of a
' raised exception, we still need to close the instance of the
' SqlConnection object...we can do that here. If we try to
' Return anywhere in a Try..Catch block, Finally will still be
' executed.
conn.Close()
End Try
' We only get this far if an exception was not thrown. The Finally
' block above was executed and the connection was closed.
DoSomethingWithTheDataSet(ds)
HTH! :)
Mythran