473,545 Members | 1,924 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Try ... Catch ... Finally confusion

I got caught with my pants down the other day when trying to explain
Try...Catch...F inally and things didn't work as I had assumed. Perhaps
someone can explain to me the purpose of Finally. I've looked at several
texts that I have and none of them address this specific point.

If I call some method that throws an exception in my routine Foo,

sub foo
call bar <- throws an exception
do something else <- never get here
end sub

control is passed back up the call stack to the first valid catch block.
So far so good.

Now if I do this

sub foo
try
call bar (which throws an exception)
catch
handle the exception <- only if exception thrown
end try

do something else <- since exception handled, do this

end sub

execution goes to the catch block and then continues to do something
else. So far so good.

If I do this

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
Nov 21 '05 #1
7 1708
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 = GetDataFromData base(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.
DoSomethingWith TheDataSet(ds)

HTH! :)

Mythran

Nov 21 '05 #2
Finally always runs even if you are in a function and perform a hard return
statement finally is run ,, so it is the perfect place to put in code that
should run nomather what ( for example object cleanup code )

regrds

Michel Posseth

"Sean Kirkpatrick" <na**********@c ommunity.nospam > wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I got caught with my pants down the other day when trying to explain
Try...Catch... Finally and things didn't work as I had assumed. Perhaps
someone can explain to me the purpose of Finally. I've looked at several
texts that I have and none of them address this specific point.

If I call some method that throws an exception in my routine Foo,

sub foo
call bar <- throws an exception
do something else <- never get here
end sub

control is passed back up the call stack to the first valid catch block.
So far so good.

Now if I do this

sub foo
try
call bar (which throws an exception)
catch
handle the exception <- only if exception thrown
end try

do something else <- since exception handled, do this

end sub

execution goes to the catch block and then continues to do something else.
So far so good.

If I do this

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


Nov 21 '05 #3
Sometimes you don't want to handle the error at this function. That is,
you'll handle it somewhere else up the chain. If this happens, you
still need to clean up everything. Also, you don't have to use Catch in
a Try statement.

Try

Cursors.Current = Cursor.WaitCurs or
ListView1.Begin Update()

' Do stuff.

Finally
Cursors.Current = Cursor.Default
ListView1.EndUp date()
End Try

Nov 21 '05 #4
On Wed, 21 Sep 2005 10:39:05 -0700, Sean Kirkpatrick <na**********@c ommunity.nospam > wrote:
¤ If I do this
¤
¤ 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!

Yes, Finally always executes when the flow of control leaves the Try statement. It is an optional
keyword.

It guarantees the execution of code in the Finally block if an exception is generated in the Catch
block or when you execute an Exit Try statement.
Paul
~~~~
Microsoft MVP (Visual Basic)
Nov 21 '05 #5
Paul Clement wrote:
¤ I can see no use for Finally!

It guarantees the execution of code in the Finally block if an exception is generated in the Catch
block or when you execute an Exit Try statement.

Ok, this answer makes some sense - if I'm in a Catch block and *another*
exception occurs, Finally will ensure that the original cleanup code
gets called, though I submit that in the case of Exit Try, there is no
difference between my original examples 2 & 3.

I'm going to have to play with it a bit to grock it completely.

Thanks Paul!

Sean
Nov 21 '05 #6
On 2005-09-21, Sean Kirkpatrick <na**********@c ommunity.nospam > wrote:
Paul Clement wrote:
¤ I can see no use for Finally!

It guarantees the execution of code in the Finally block if an exception is generated in the Catch
block or when you execute an Exit Try statement.
Ok, this answer makes some sense - if I'm in a Catch block and *another*
exception occurs, Finally will ensure that the original cleanup code
gets called,


Keep in mind that often *another* exception is your own...

Try
DoSomething()
Catch(ex As Exception)
LogSomeInformat ion(ex.Message)
Throw
Finally
CleanUp()
End Try

....or, something I commonly do...

Try
DoSomething()
Catch(ex as Exception)
Throw New SpecificExcepti onType(ex)
Finally
....

though I submit that in the case of Exit Try, there is no
difference between my original examples 2 & 3.


They are, but that's because you're eating the exception, which should
be a very, very rare thing. Usually, Try-Finally blocks are much more
common than Try-Catch blocks..

Try
DoSomething()
Finally
' do your cleanup, and let the exception propagate up
....

Nov 21 '05 #7
Sean,

Know that you can set a try block in a try block

\\\
Try
connection.open
Try
do the reading
Catch
reader errohandling
return
End Try
Catch
connection open error handling
Finally
connection close 'this will always be done whatever error
End Try
///

I hope this helps,

Cor
Nov 21 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2767
by: ChrisB | last post by:
Hello All: I notice that when using try/catch blocks in C#, variables declared in the try block go out of scope in the finally block. So, for example, the following code generates a compiler error: try { SqlDataReader sqlDataReader = new SqlDataReader(sqlConnection,
8
2721
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block? (ie, forget the finally block and just end the try/catch and put the code after the try/catch block). Or does the "finally" construct add some...
6
7121
by: Tilfried Weissenberger | last post by:
Hi, I am a bit confused as to what the FINALLY block is meant for. What's the difference between: this.Cursor = Cursors.WaitCursor; try { //do some stuff } catch { //handle exception } finally { this.Cursor = Cursors.Default; }
11
3462
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
23
3042
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally block. But, I prefer to dim them "on the fly" only if needed (save as much resources as possible). A little further... I may wish to create a sqlcommand...
13
1564
by: Woody Splawn | last post by:
I have a try catch statement in a fucntion that is supposed to return a true or a false My code looks like this: Try mySqlConnection.Open() Dim Da1 As New SqlDataAdapter("Select JnlType, Description from JnlType", mySqlConnection) Dim Ds As New DataSet("X")
32
6096
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I understand Finally runs whether an error was caught or not, I haven't found a use for finally yet.
6
7433
by: foolmelon | last post by:
If a childThread is in the middle of a catch block and handling an exception caught, the main thread calls childThread.Abort(). At that time a ThreadAbortException is thrown in the childThread. The question is: after the ThreadAbortException is thrown, does the childThread continue run the remaining code in the catch block?
12
2648
by: David Lozzi | last post by:
Howdy, I ran into a very interesting issue and I'm curios as to how this is suppose to work. I am using Try...Catch...Finally statements for all database connectivity in my ASP.NET 2.0 web application. I'm connecting to IBM's Universe 10.2 using UniObjects.Net. Anyway, if the connection errors, the Finally closes the connection. What I see...
0
7410
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7668
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3466
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.