473,763 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Try Catch

The use of Try in the Finally part - is that overkill?. I think of the
code failing before opening sqlCon - that would generate an error in
the Finally part. How would Finally handle that?
Try
Dim cmd As New SqlCommand
cmd.CommandText = "spSetAdLin ks"
cmd.CommandType = Data.CommandTyp e.StoredProcedu re
cmd.Connection = sqlCon

sqlCon.Open()

AdList = cmd.ExecuteRead er

Catch ex As Exception
AdList = Nothing
Finally
Try
sqlCon.Close()
sqlCon.Dispose( )
Catch ex As Exception
End Try
End Try
/Morten
Jan 5 '07 #1
5 2319
A more reliable way to handle it is:

...
Finally
If sqlCon.State <SqlConnectionS tate.Closed Then sqlCon.Close()
End Try

and even more reliable:

...
Finally
If sqlCon IsNot Nothing AndAlso sqlCon.State <ConnectionStat e.Closed
Then sqlCon.Close()
End Try

The documentation states that the Close and Dispose methods of the
SqlConnection are functionally equivalent so you don't need to call both
methods. It is a matter of chaoice as to which one you call but I prefer
Close.
"Morten Snedker" <morten_spammen ot_ATdbconsult. dkwrote in message
news:jt******** *************** *********@4ax.c om...
The use of Try in the Finally part - is that overkill?. I think of the
code failing before opening sqlCon - that would generate an error in
the Finally part. How would Finally handle that?
Try
Dim cmd As New SqlCommand
cmd.CommandText = "spSetAdLin ks"
cmd.CommandType = Data.CommandTyp e.StoredProcedu re
cmd.Connection = sqlCon

sqlCon.Open()

AdList = cmd.ExecuteRead er

Catch ex As Exception
AdList = Nothing
Finally
Try
sqlCon.Close()
sqlCon.Dispose( )
Catch ex As Exception
End Try
End Try
/Morten

Jan 5 '07 #2
Morten Snedker wrote:
The use of Try in the Finally part - is that overkill?
In this case, yes. Getting rid of a Connection can't go [that] far
wrong. :-)

However, it probably reads better to check for a null object before
calling the method and handling the possible Exception, as in

Finally

If Not ( sqlCon Is Nothing ) Then ' still VB'2003
sqlCon.Dispose( ) ' It's got a Dispose method - use it ;-)
End If

End Try

Also, I would advise /against/ the use of empty Catch blocks - ever.
If nothing else, put a comment inside them so that, in months to come,
you remind yourself (or someone else!) why you're prepared to ignore a
particular Exception in a particular circumstance, as in (AspNet example):

Try
Response.Redire ct( "http://somewhere/...", True )

Catch ex as ThreadAbortExce ption
' Thrown by Response.Redire ct
' Do Nothing

End Try

HTH,
Phill W.
Jan 5 '07 #3
Morten,

In this case there's no need for a nested try-catch. All you need to
do is call Dispose. Like all properly implemented Dispose methods the
SqlConnection.D ispose will not throw exceptions.

Brian

Morten Snedker wrote:
The use of Try in the Finally part - is that overkill?. I think of the
code failing before opening sqlCon - that would generate an error in
the Finally part. How would Finally handle that?
Try
Dim cmd As New SqlCommand
cmd.CommandText = "spSetAdLin ks"
cmd.CommandType = Data.CommandTyp e.StoredProcedu re
cmd.Connection = sqlCon

sqlCon.Open()

AdList = cmd.ExecuteRead er

Catch ex As Exception
AdList = Nothing
Finally
Try
sqlCon.Close()
sqlCon.Dispose( )
Catch ex As Exception
End Try
End Try
/Morten
Jan 5 '07 #4
Typically, all code except for simple variable declarations should
occur within Try Blocks. This impoves the user experience when
problems occur and greatly simplifies debugging problems. However,
exception handling does incur a slight performance penalty.

Problem 1 your code:
Variable Declaration should be moved "OutSide" of the Try Block. This
is neccessary because the Finally block cannot access variables that
are declared within the Try block.

Example:

Dim cmd as New SqlConnection
Try
Catch
Finally
End Try

Problem 2 your code:
To close database connects, use the connection object's Close method.
Technically, you can also call the Dispose method of the connection
object to close the connection, but the preferred techinique is to call
the Close method.

You do not need to use Both SQLConn.Close, and SQLConn.Dispose

The OverKill:
The Finally block runs after the try block and any catch blocks have
finished executing. You should use the Finally block to close any open
objects. You do not need to place a try block in the Finally block.

Advice:
1. You can inspect the value of the connections current state. By
creating an event handler, or use an if statement, such as:

If sqlCon..State = ConnectionState .Open then
'do something
End if

2. You can catch an SQL exception. And inspect the
SQLException.Er rors property to access a collection of error that are
returned from the SQL server.

Morten Snedker wrote:
The use of Try in the Finally part - is that overkill?. I think of the
code failing before opening sqlCon - that would generate an error in
the Finally part. How would Finally handle that?
Try
Dim cmd As New SqlCommand
cmd.CommandText = "spSetAdLin ks"
cmd.CommandType = Data.CommandTyp e.StoredProcedu re
cmd.Connection = sqlCon

sqlCon.Open()

AdList = cmd.ExecuteRead er

Catch ex As Exception
AdList = Nothing
Finally
Try
sqlCon.Close()
sqlCon.Dispose( )
Catch ex As Exception
End Try
End Try
/Morten
Jan 5 '07 #5
Morten,

The way you do it is almost the same as using the Using.
(Using connection)

Using connection As New SqlConnection(c onnectionString )
connection.Open ()
End using

However if you want it catched, than I would go for

Try
connection
try handling
catch handling
catch connection
finaly
close connection
Cor

Jan 6 '07 #6

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

Similar topics

10
30313
by: Gary.Hu | last post by:
I was trying to catch the Arithmetic exception, unsuccessfully. try{ int a = 0, b = 9; b = b / a; }catch(...){ cout << "arithmetic exception was catched!" << endl; } After ran the program, it quitted with core dumped. %test
11
6894
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill non-supporting browsers? TIA -- --
4
4345
by: Abhishek Srivastava | last post by:
Hello All, I have seen code snippets like try { ..... } catch {
11
3491
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) {}
13
3721
by: Benny | last post by:
Hi, I have something like this: try { // some code } catch // note - i am catching everything now {
23
3083
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 and datareader object ONLY if certain conditions are met. But, if I want to clean these up in the...
32
6127
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.
23
2331
by: pigeonrandle | last post by:
Hi, Does this bit of code represent complete overkill?! try { //create a treenode TreeNode tn = new TreeNode(); //add it to a treeview tv.Nodes.Add(tn);
0
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9389
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10149
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10003
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9943
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9828
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8825
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2797
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.