473,385 Members | 1,727 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Problems with try...catch

Greetings,

I'm having an issue in C#. I'm using ADO.NET but that seems secondary to the
issue.

The following code:

SqlConnection conn;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
conn.Close();
}

Won't compile. The compiler complains that conn is used (within the finally
block) without having been initialized (or something to that effect). So I
looked at some examples in some books I have and they move the conn.Open()
prior to the try block.

Well, that compiles okay. But then what happens if the connection cannot be
opened? That error would not be caught.

Am I missing anything?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
Jan 9 '07 #1
11 1407
I think you snipped away the problem...
I think you originally had:

SqlConnection conn;
try {
conn = new SqlConnection(cs);
conn.Open();
...
} finally {
conn.Close();
}

The problem is that if the first line errors then conn will not have
been initialised. You could get around this by moving the initialiser
into the variable declaration line, but a better option is "using"
since this also manages disposal (which inclused closure), hence:

using(SqlConnection conn = new SqlConnection(cs)) {
conn.Open();
...
conn.Close();
}

For a full explanation, look up "using" and "Dispose".

Marc

Jan 9 '07 #2
RH
This will solve your problem:

SqlConnection conn = null;
try
{
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}

but you really should be using the "using" keyword for these kinds of
things:

using (SqlConnection conn = new SqlConnection(...))
{
//...
}

"Jonathan Wood" <jw***@softcircuits.comwrote in message
news:u5**************@TK2MSFTNGP02.phx.gbl...
Greetings,

I'm having an issue in C#. I'm using ADO.NET but that seems secondary to
the issue.

The following code:

SqlConnection conn;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
conn.Close();
}

Won't compile. The compiler complains that conn is used (within the
finally block) without having been initialized (or something to that
effect). So I looked at some examples in some books I have and they move
the conn.Open() prior to the try block.

Well, that compiles okay. But then what happens if the connection cannot
be opened? That error would not be caught.

Am I missing anything?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 9 '07 #3
SqlConnection conn = null;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
if(null!=conn)
{
conn.Close();
}
}

You can try that, or the "using" statement.


"Jonathan Wood" <jw***@softcircuits.comwrote in message
news:u5**************@TK2MSFTNGP02.phx.gbl...
Greetings,

I'm having an issue in C#. I'm using ADO.NET but that seems secondary to
the
issue.

The following code:

SqlConnection conn;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
conn.Close();
}

Won't compile. The compiler complains that conn is used (within the
finally
block) without having been initialized (or something to that effect). So I
looked at some examples in some books I have and they move the conn.Open()
prior to the try block.

Well, that compiles okay. But then what happens if the connection cannot
be
opened? That error would not be caught.

Am I missing anything?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com


Jan 9 '07 #4
See http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!126.entry.

Mark.
--
http://www.markdawson.org
"Jonathan Wood" wrote:
Greetings,

I'm having an issue in C#. I'm using ADO.NET but that seems secondary to the
issue.

The following code:

SqlConnection conn;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
conn.Close();
}

Won't compile. The compiler complains that conn is used (within the finally
block) without having been initialized (or something to that effect). So I
looked at some examples in some books I have and they move the conn.Open()
prior to the try block.

Well, that compiles okay. But then what happens if the connection cannot be
opened? That error would not be caught.

Am I missing anything?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
Jan 9 '07 #5
Actually, that could break the "finally" if the conn is never
successfully created (i.e. conn is null when conn.Close() is invoked).
I would recommend the "using" approach as it deals with this for you.
If you want you can still use the following inside the "using".

conn.Open();
try {
...
} finally {
conn.Close()
}

Marc
Jan 9 '07 #6
Actually, that could break the "finally" if the conn is never
successfully created (i.e. conn is null when conn.Close() is invoked).
I would recommend the "using" approach as it deals with this for you.
If you want you can still use the following inside the "using".
This is a much better approach, and using blocks have their own
try/catch/finally code built-in behind the scenes.

using(SqlConnection conn = new SqlConnection("...")) {
conn.Open();
...
}

Because the SqlConnection class implements IDisposable, the compiler
can write code to catch an error ( say the server can't be reached and
your open call fails ) and destroy the connection, if it exists.

Jan 9 '07 #7
Yes Marc, I did lose one line that was in question.

I'm not really sure what the using keyword has to do with either error
handling or Dispose, but will research them further.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Marc Gravell" <ma**********@gmail.comwrote in message
news:11*********************@11g2000cwr.googlegrou ps.com...
>I think you snipped away the problem...
I think you originally had:

SqlConnection conn;
try {
conn = new SqlConnection(cs);
conn.Open();
...
} finally {
conn.Close();
}

The problem is that if the first line errors then conn will not have
been initialised. You could get around this by moving the initialiser
into the variable declaration line, but a better option is "using"
since this also manages disposal (which inclused closure), hence:

using(SqlConnection conn = new SqlConnection(cs)) {
conn.Open();
...
conn.Close();
}

For a full explanation, look up "using" and "Dispose".

Marc

Jan 10 '07 #8
Thanks but that article doesn't address the issue I'm raising. I understand
reference type variables must be initialized before being used. The issue
was how to do this and still have code that could fail wrapped in
try...catch.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Mark R. Dawson" <Ma*********@discussions.microsoft.comwrote in message
news:C3**********************************@microsof t.com...
See
http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!126.entry.

Mark.
--
http://www.markdawson.org
"Jonathan Wood" wrote:
>Greetings,

I'm having an issue in C#. I'm using ADO.NET but that seems secondary to
the
issue.

The following code:

SqlConnection conn;
try
{
conn.Open();
// ...
}
catch (Exception err)
{
// ...
}
finally
{
conn.Close();
}

Won't compile. The compiler complains that conn is used (within the
finally
block) without having been initialized (or something to that effect). So
I
looked at some examples in some books I have and they move the
conn.Open()
prior to the try block.

Well, that compiles okay. But then what happens if the connection cannot
be
opened? That error would not be caught.

Am I missing anything?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 10 '07 #9
Jonathan Wood <jw***@softcircuits.comwrote:
Yes Marc, I did lose one line that was in question.

I'm not really sure what the using keyword has to do with either error
handling or Dispose, but will research them further.
"using" has two uses:

1) The using directive which makes namespaces (and members etc)
available without specifying the namespace when a type is used.

2) The using statement which is an automatically try/finally which
calls Dispose on implementations of IDisposable automatically.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #10
What if I want a catch block? What would that look like?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Jonathan Wood <jw***@softcircuits.comwrote:
>Yes Marc, I did lose one line that was in question.

I'm not really sure what the using keyword has to do with either error
handling or Dispose, but will research them further.

"using" has two uses:

1) The using directive which makes namespaces (and members etc)
available without specifying the namespace when a type is used.

2) The using statement which is an automatically try/finally which
calls Dispose on implementations of IDisposable automatically.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Jan 10 '07 #11
Jonathan Wood <jw***@softcircuits.comwrote:
What if I want a catch block? What would that look like?
In that case you'd need to put a try/catch either inside or outside the
using statement - there isn't a "using with catch".

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 10 '07 #12

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

Similar topics

3
by: Alan Krueger | last post by:
Greetings, I've been able to cache Transformer objects in a Tomcat-based servlet application to avoid unnecessary Transformer rebuilding, except for certain ones on certain machines. I'm...
6
by: Daniel Wilson | last post by:
I am having exception-handling and stability problems with .NET. I will have a block of managed code inside try...catch and will still get a generic ..NET exception box that will tell me which...
0
by: Jesper Stocholm | last post by:
I am using the example as the basis for an application I am currently writing. The setup consists of two applications (client and server) that talk to each other thru TCP. I have no problems...
0
by: Sergej Pioch | last post by:
Hello everybody, im trying hard to automate some tasks in a huge windows environment. This lend me to bigger problems while trying to create new global security groups within active directory....
5
by: Chua Wen Ching | last post by:
Hi, I read from this tutorial at codeproject Question A: http://www.codeproject.com/csharp/GsXPathTutorial.asp regarding xpath.. but i try to apply in my situation, and can't get it...
2
by: Rick | last post by:
Hi, I'm trying to get a simple UdpClient app working. I've been looking at the MSDN info regarding UdpClient. When I set it up on my own PC and send messages to myself it works OK. If I try to...
5
by: Elmo Watson | last post by:
I'm having weird problems emailing on the Win2003 Staging environment - - the same script runs on multiple other computers, but on this one, the smtp service is running, but when the send is done...
0
by: ZR | last post by:
I am writing two applications which needs to (among other things) communicate through network, so one of them is a client and the other one is a server. I have used asynchronous socket examples...
0
by: Sergistm | last post by:
Hello World, :D I have a problem that it is making me crazy, I hope you can help me. I'm trying to execute a .exe file with the Procces.Start, and there is no problem when the file is on my...
10
by: jodleren | last post by:
Hi I know, that there are a lot of people having problems with orkut.com, errors like "object expected" and named objects missing. When loading the site can generate some 10 errors, and still...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.