473,804 Members | 2,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Try Catch Finally Using

All the code samples I can find show using on its own or try... catch..
..finally on its own. Will the following cover me properly in terms of
handling errors and cleaning up?

string conns = "Provider=Micro soft.Jet.OleDb. 4.0;Data
Source=|DataDir ectory|Northwin d.mdb";
try
{
using (OleDbConnectio n conn = new OleDbConnection (conns))
{
OleDbCommand cmd = new OleDbCommand("S ELECT * From FOO", conn);
conn.Open();
OleDbDataReader rd = cmd.ExecuteRead er();
//do stuff
}
}
catch (Exception ex)
{
Response.Write( ex.Message);
}

Clearly Access and Response.Write are just being used for demo purposes...

Nov 16 '07 #1
4 4178
Mike,

In this sample, if there is an error in the code, the connection will
have Dispose called on it (personally, I like to place the command and
reader in using statements as well) when the scope is exited.

If the using statement is exited as the result of an exception, then the
catch block will be executed in this case.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Mike" <bl***@blank.bl ankwrote in message
news:ud******** ******@TK2MSFTN GP06.phx.gbl...
All the code samples I can find show using on its own or try... catch..
.finally on its own. Will the following cover me properly in terms of
handling errors and cleaning up?

string conns = "Provider=Micro soft.Jet.OleDb. 4.0;Data
Source=|DataDir ectory|Northwin d.mdb";
try
{
using (OleDbConnectio n conn = new OleDbConnection (conns))
{
OleDbCommand cmd = new OleDbCommand("S ELECT * From FOO", conn);
conn.Open();
OleDbDataReader rd = cmd.ExecuteRead er();
//do stuff
}
}
catch (Exception ex)
{
Response.Write( ex.Message);
}

Clearly Access and Response.Write are just being used for demo purposes...
Nov 16 '07 #2
Well, cmd and rd are disposable too, so you could be "using" them as
well:

using (OleDbConnectio n conn = new OleDbConnection (conns))
using (OleDbCommand cmd = new OleDbCommand("S ELECT * From FOO", conn))
{ // just to highlight you don't need a new brace/indent each time...
conn.Open();
using(OleDbData Reader rd = cmd.ExecuteRead er()) {
//do stuff
}
}

I'm assuming that you simply want to log the error to the response (as
it won't get re-thrown by default). Note that in 1.1 you can get
exceptions (from managed C++ for example) that aren't Exception based,
so your "catch" might not fire. In 2.0 such exceptions get
automatically wrapped for you by default, so this isn't a problem.

But other than than, looks fine...

Marc
Nov 16 '07 #3
"Mike" <bl***@blank.bl ankschrieb im Newsbeitrag
news:ud******** ******@TK2MSFTN GP06.phx.gbl...
All the code samples I can find show using on its own or try... catch..
.finally on its own. Will the following cover me properly in terms of
handling errors and cleaning up?

string conns = "Provider=Micro soft.Jet.OleDb. 4.0;Data
Source=|DataDir ectory|Northwin d.mdb";
try
{
using (OleDbConnectio n conn = new OleDbConnection (conns))
{
OleDbCommand cmd = new OleDbCommand("S ELECT * From FOO", conn);
conn.Open();
OleDbDataReader rd = cmd.ExecuteRead er();
//do stuff
}
The using statement ensures, that the resource (in this case, the
OleDbConnection ) is disposed on exiting the block of the using statement.
This will work indepently of how the block is exited, wether by normal flow,
an exception or a jumpstatement or what else.
}
catch (Exception ex)
{
Response.Write( ex.Message);
}
This block will handle any excption wich falls out of the try block. Because
it is a general catch block, no exception whatsoever occuring inside the try
block will exit the try-catch-statement.
It this is a good approach can be doubted ;-)

The error handling will occur directly after the disposing of the connection
(if it occured inside the using block).
>
Clearly Access and Response.Write are just being used for demo purposes...
I hope so ;-)

Does this make it clearer to you?

Christof

Nov 16 '07 #4
Thank you to everyone :-)

Mike

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in
message news:BD******** *************** ***********@mic rosoft.com...
Mike,

In this sample, if there is an error in the code, the connection will
have Dispose called on it (personally, I like to place the command and
reader in using statements as well) when the scope is exited.

If the using statement is exited as the result of an exception, then
the catch block will be executed in this case.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Mike" <bl***@blank.bl ankwrote in message
news:ud******** ******@TK2MSFTN GP06.phx.gbl...
>All the code samples I can find show using on its own or try... catch..
.finally on its own. Will the following cover me properly in terms of
handling errors and cleaning up?

string conns = "Provider=Micro soft.Jet.OleDb. 4.0;Data
Source=|DataDi rectory|Northwi nd.mdb";
try
{
using (OleDbConnectio n conn = new OleDbConnection (conns))
{
OleDbCommand cmd = new OleDbCommand("S ELECT * From FOO", conn);
conn.Open();
OleDbDataReader rd = cmd.ExecuteRead er();
//do stuff
}
}
catch (Exception ex)
{
Response.Write( ex.Message);
}

Clearly Access and Response.Write are just being used for demo
purposes...

Nov 16 '07 #5

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

Similar topics

6
7133
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
3494
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
3084
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...
13
1587
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")
34
4888
by: Bob | last post by:
Hi, The compiler gives Warning 96 Variable 'cmdSource' is used before it has been assigned a value. A null reference exception could result at runtime. Dim cmdSource as SQlClient.SQLDataReader Try Set up the database read and do it. Catch ex as system.exception exception stuff here Finally
32
6132
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
7451
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?
28
3848
by: RickHodder | last post by:
I'm getting frustrated with using try...catch with local variables: The code below wont compile in .NET 1.1: I get the following error: "Use of unassigned local variable 'oProcessFileReader' " Is there a way around this error? <code> private void Test(string sFileName) {
12
2699
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 happening is that the function in the Finally statement either isn't running or doesn't apply what...
8
2484
by: =?Utf-8?B?U2F2dm91bGlkaXMgSW9yZGFuaXM=?= | last post by:
Is it right when placing the RETURN statement inside the TRY or inside the CATCH statement, when there is a FINALLY clause? Especially when there is a transaction going on, in the try/catch block? I give you the following example to meka it more clear: (I use Enterprise Library, but the same also applies without it) public function f_SomeFunction(parm1,....) as integer dim tr as DbTransaction
0
9711
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
9593
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
10343
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
10335
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
10088
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
5529
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
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.