473,397 Members | 2,099 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,397 software developers and data experts.

troubles with finally statement and objects

Hi,

I am using the try catch finally block in many places in my code.

When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.

dr.close();
works fine in the try but not in the finally.

How can I access my local objects in the finally without these errors?

thanks

Chris
Nov 17 '05 #1
16 2439
Chris,

You should be doing something like this:

// Delcare the reader.
SqlDataReader reader = null;

// Use the reader here.
try
{
// Create the reader.
reader = new SqlDataReader(...);

// Use the reader.
}
catch
{
}
finally
{
// Check the reader for null. If it is not, then
// dispose.
if (reader != null)
{
// Dispose of it.
((IDisposable) reader).Dispose();
}
}

This should compile just fine. Chances are you missed the null
assignment to the variable declaration.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Chris" <Ch***@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
Hi,

I am using the try catch finally block in many places in my code.

When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.

dr.close();
works fine in the try but not in the finally.

How can I access my local objects in the finally without these errors?

thanks

Chris

Nov 17 '05 #2
Looks like the variable dr is declared inside try block - dr is only local
to try {} and not accessible in finally block. For your case, decalre dr
outside the try block so that you can access it in both try as well as
finally blocks.

"Chris" <Ch***@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
Hi,

I am using the try catch finally block in many places in my code.

When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.

dr.close();
works fine in the try but not in the finally.

How can I access my local objects in the finally without these errors?

thanks

Chris
Nov 17 '05 #3
"Chris" <Ch***@discussions.microsoft.com> wrote in message
news:FF**********************************@microsof t.com...
Hi,

I am using the try catch finally block in many places in my code.

When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.

dr.close();
works fine in the try but not in the finally.

How can I access my local objects in the finally without these errors?


Hi Chris,

In addition to the excellent answers given so far, there is another
construct of C# that you may not be aware of.

You are clearly being a good citizen and cleaning up the data reader during
error handling. However, C# has a pretty nice construct that will call the
..Dispose method for you... it is called 'using'

I snatched a bad example of using the Data Reader object from a random site
and rewrote it to use the 'using' statement, here:

SqlDataReader data;
using (data = command.ExecuteReader(CommandBehavior.CloseConnect ion))
{
while( data.Read() )

{
Console.WriteLine("Company Name " +
data.GetString(data.GetOrdinal("CompanyName"));

}
} // automatically calls data.Dispose();

Here is the spec page in the MSDN. It's a very cool capability of the
language, and reduces your code brilliantly.
Note: you still need a try-catch-finally, but you won't need to close the
data reader, because leaving that block of 'using' code, FOR ANY REASON,
will call Dispose for you.

http://msdn.microsoft.com/library/de...pspec_8_13.asp
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #4
Nick Malik [Microsoft] <ni*******@hotmail.nospam.com> wrote:
I snatched a bad example of using the Data Reader object from a random site
and rewrote it to use the 'using' statement, here:

SqlDataReader data;
using (data = command.ExecuteReader(CommandBehavior.CloseConnect ion))
{
while( data.Read() )

{
Console.WriteLine("Company Name " +
data.GetString(data.GetOrdinal("CompanyName"));

}
} // automatically calls data.Dispose();
That would be better written IMO as:

using (SqlDataReader data = command.ExecuteReader
(CommandBehavior.CloseConnection))
{
while( data.Read() )
{
Console.WriteLine("Company Name " +
data.GetString(data.GetOrdinal("CompanyName"));

}
} // automatically calls data.Dispose();

There's no point in letting the variable have a wider scope than the
using block, and it's better to give it the smallest scope it needs.
Here is the spec page in the MSDN. It's a very cool capability of the
language, and reduces your code brilliantly.


Agreed.
--
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
Nov 17 '05 #5
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
That would be better written IMO as:

using (SqlDataReader data = command.ExecuteReader
(CommandBehavior.CloseConnection))
{
while( data.Read() )
{
Console.WriteLine("Company Name " +
data.GetString(data.GetOrdinal("CompanyName"));

}
} // automatically calls data.Dispose();

There's no point in letting the variable have a wider scope than the
using block, and it's better to give it the smallest scope it needs.


Thanks, Jon. That's what I get for rewriting something I snatch off of a
web site. I agree with your change completely.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #6

"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in message
news:_t********************@comcast.com...
SqlDataReader data;
using (data = command.ExecuteReader(CommandBehavior.CloseConnect ion))
{
while( data.Read() )

{
Console.WriteLine("Company Name " +
data.GetString(data.GetOrdinal("CompanyName"));

}
} // automatically calls data.Dispose();


Why don't I like that? Is it because it's new and I'm not used to it? I want
to see the call to Close() in there somewhere. Am I becoming old and set in
my ways?
Nov 17 '05 #7
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:

<snip using statement example>
Why don't I like that? Is it because it's new and I'm not used to it? I want
to see the call to Close() in there somewhere. Am I becoming old and set in
my ways?


I hope it's just because you're not used to it. The "using" statement
is one of the top things I prefer about C# to Java, despite it only
being syntactic sugar. It makes things *much* more readable (admittedly
only when you know what the using statement does!), and makes it far
simpler to "get it right" when it comes to disposing of things.

--
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
Nov 17 '05 #8

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
It makes things *much* more readable (admittedly
only when you know what the using statement does!), and makes it far
simpler to "get it right" when it comes to disposing of things.


I know what "using" does, so I don't think that's it. I don't know what
happens in Dispose() of every single class in the .NET library. Perhaps
that's it. I'd like to see Close() then Dispose() to be sure Close()
actually happened. Perhaps this is paranoia on my part. If so, hopefully
I'll get over it.
Nov 17 '05 #9
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
It makes things *much* more readable (admittedly
only when you know what the using statement does!), and makes it far
simpler to "get it right" when it comes to disposing of things.


I know what "using" does, so I don't think that's it. I don't know what
happens in Dispose() of every single class in the .NET library. Perhaps
that's it. I'd like to see Close() then Dispose() to be sure Close()
actually happened. Perhaps this is paranoia on my part. If so, hopefully
I'll get over it.


If Dispose() doesn't correctly deal with a resource, then it's a bug -
but you could just as easily have the bug in Close as in Dispose. Note
that making sure you call both Close *and* Dispose involves having
*two* finally blocks, making the code even harder to read :)

As you say, hopefully you'll get over it :)

--
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
Nov 17 '05 #10
Chris,

You can set a try block nested which is very nice for this kind of
operations.

try{open whatever;
try{}catch{}
}
catch{}
finally{close whatever;}

I hope this helps,

Cor
Nov 17 '05 #11
Thanks Everyone for your responses.

I am having trouble finding the namespace that provides me with the
command: CommandBehavior.CloseConnection.

I'm getting the type or namespace missing error.
Could someone direct me how get it up and running. I have a hunch it's not
really
my namespace missing but a scope issue?

thanks

chris

"Chris" wrote:
Hi,

I am using the try catch finally block in many places in my code.

When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.

dr.close();
works fine in the try but not in the finally.

How can I access my local objects in the finally without these errors?

thanks

Chris

Nov 17 '05 #12
Chris <Ch***@discussions.microsoft.com> wrote:
Thanks Everyone for your responses.

I am having trouble finding the namespace that provides me with the
command: CommandBehavior.CloseConnection.

I'm getting the type or namespace missing error.
Could someone direct me how get it up and running. I have a hunch it's not
really my namespace missing but a scope issue?


CommandBehavior is an enumeration in the System.Data namespace.

If that doesn't help, perhaps you could give an example of how you're
trying to use it?

--
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
Nov 17 '05 #13
Jon wrote:
using (SqlDataReader data = command.ExecuteReader
(CommandBehavior.CloseConnection))


What would happen if the ExecuteReader command returned null? Does the
using construct check for null before it calls .Dispose?

Nov 17 '05 #14

"Chris Dunaway" <du******@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Jon wrote:
using (SqlDataReader data = command.ExecuteReader
(CommandBehavior.CloseConnection))
What would happen if the ExecuteReader command returned null?


I don't see "null" listed as a possible return value.
Does the
using construct check for null before it calls .Dispose?


In general, I would expect to get an exception if the "using" statement was
executed on "null".
Nov 17 '05 #15
Chris Dunaway <du******@gmail.com> wrote:
Jon wrote:
using (SqlDataReader data = command.ExecuteReader
(CommandBehavior.CloseConnection))


What would happen if the ExecuteReader command returned null? Does the
using construct check for null before it calls .Dispose?


Yes. From the C# spec (reformatted with sane bracing):

<quote>
A using statement of the form

using (R r1 = new R())
{
r1.F();
}

is precisely equivalent to

R r1 = new R();
try
{
r1.F();
}
finally
{
if (r1 != null) ((IDisposable)r1).Dispose();
}
</quote>

--
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
Nov 17 '05 #16
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
Does the
using construct check for null before it calls .Dispose?


In general, I would expect to get an exception if the "using" statement was
executed on "null".


No - you won't get an exception unless the body of the using statement
tries to dereference the null value.

--
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
Nov 17 '05 #17

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

Similar topics

18
by: David Buchan | last post by:
Hi guys, This may be a dumb question; I'm just getting into C language here. I wrote a program to unpack a binary file and write out the contents to a new file as a list of unsigned integers....
16
by: Ken | last post by:
What is the purpose of a finally block in try-catch- finally? I am confused because, if I am reading the definition correctly, this block seems unnecessary. Consider the following from the Visual...
10
by: RepStat | last post by:
If I have code such a SqConnection cndb = new SqlConnection(connstr) SqlDataReader dr = null tr cndb.Open() SqlCommand cmd = new SqlCommand("exec mysp", cndb) dr = cmd.ExecuteReader()
23
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...
26
by: Grim Reaper | last post by:
Just a quick and probably daft question... Isn't the code; Try DoSomething() Catch e As Exception HandleError(e) Finally DoThisAtTheEnd()
15
by: tshad | last post by:
Do I still need to close an object in a finally statement after a catch if it is part of a using statement? For example: FileStream fs = null; try { using (FileInfo fInfo = new...
5
by: Hillbilly | last post by:
MSDN Remarks "as a rule" the using statement should be used when instantiating objects which inherit IDisposable. Other than the obvious unmanaged objects like the file system example, fonts and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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
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...
0
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,...

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.