473,569 Members | 2,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2453
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.co m

"Chris" <Ch***@discussi ons.microsoft.c om> wrote in message
news:FF******** *************** ***********@mic rosoft.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***@discussi ons.microsoft.c om> wrote in message
news:FF******** *************** ***********@mic rosoft.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***@discussi ons.microsoft.c om> wrote in message
news:FF******** *************** ***********@mic rosoft.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.Execute Reader(CommandB ehavior.CloseCo nnection))
{
while( data.Read() )

{
Console.WriteLi ne("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*******@hotm ail.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.Execute Reader(CommandB ehavior.CloseCo nnection))
{
while( data.Read() )

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

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

using (SqlDataReader data = command.Execute Reader
(CommandBehavio r.CloseConnecti on))
{
while( data.Read() )
{
Console.WriteLi ne("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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
That would be better written IMO as:

using (SqlDataReader data = command.Execute Reader
(CommandBehavio r.CloseConnecti on))
{
while( data.Read() )
{
Console.WriteLi ne("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*******@hotm ail.nospam.com> wrote in message
news:_t******** ************@co mcast.com...
SqlDataReader data;
using (data = command.Execute Reader(CommandB ehavior.CloseCo nnection))
{
while( data.Read() )

{
Console.WriteLi ne("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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
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.co m>
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

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

Similar topics

18
3011
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. It works on an IBM mainframe under AIX with GCC, but has trouble on Intel with GCC (DJGPP). I think it's an endian problem. The trouble is,...
16
7914
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 Studio documentation. In the first foo(), the statement in the finally block will execute even though there is an exception in the try block. In...
10
1445
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
3049
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...
26
2538
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
2107
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 FileInfo(fromImagePath + "\\" + (string)dr))
5
7125
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 the database how else may it be determined which classes and their objects inherit IDisposable? And the remarks imply the using statement is a...
0
7694
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...
0
7921
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. ...
0
8118
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...
0
7964
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...
0
6278
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...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
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
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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...

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.