Re: Try Catch Else Finally
- From: Jim Wooley <jimNOSPAMwooley@xxxxxxxxxxx>
- Date: Fri, 17 Mar 2006 19:47:51 +0000 (UTC)
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in
using try catch is that without it, or some other error handling, if a
command throws an exception the program halts with some garbage on the
screen. I've written my program with try catch around statements like
calls to other servers where something like a cable being cut might
cause the line to throw and exception as it can not execute. In the
catch I want to know what command is giving the problem. That'll help
me know what is wrong. I print a custom message to indicate what code
is being executed and the ex.message info to the screen for diagnosis.
I need to know which stored procedure will not work, or is it the
request to the remote server or did it try to parse the xml file and
find out it wasn't a xml file? The presence of an error like this can
mean skip the current record or it might mean reattempt the failed
command until it starts working.
As COR indicated, the finally block should be used to close resources and do other necessary cleanup to get your program back to a valid state. You would want to make sure to clean the resources regardless of whether a exception is thrown. Consider the following pseudocode:
dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
end try
cn.dispose
cn.close
In this case, the connection (an expensive resource) is left open if the exception is thrown. As an alternative, you can do the following
dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
finally
cn.close
cn.dispose
end try
In this case, we are assured that the connection will be closed. Starting with VB2005, we can change this as follows:
Using cn as new Connection
try
cn.open
catch
messagebox.show("Problem with connection")
end try
end using
Now we are assured that the connection is properly handled as the Using block handles the dispose for us and closes the connection. Now, if we want to simply let the exception bubble up to a calling method, we can trim this down to:
Using cn as new Connection
cn.open
end using
An exception will still be thrown, but the resource will be released correctly.
Jim Wooley
http://devauthority.com/blogs/jwooley
.
- Follow-Ups:
- Re: Try Catch Else Finally
- From: Charles Law
- Re: Try Catch Else Finally
- From: cj
- Re: Try Catch Else Finally
- References:
- Re: Try Catch Else Finally
- From: cj
- Re: Try Catch Else Finally
- Prev by Date: Re: Try Catch Else Finally
- Next by Date: Re: Try Catch Else Finally
- Previous by thread: Re: Try Catch Else Finally
- Next by thread: Re: Try Catch Else Finally
- Index(es):
Relevant Pages
|