473,503 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finally vs Using

What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within
a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom
Nov 15 '05 #1
18 1789
I believe they have no relation to each other.

"finally" is used to ensure that code gets executed regardless of whether an
exception occurred or not in a try/catch block. A using statement is just a
shortcut for way of initializing variables that rely on the Dispose method.
When the "using" block finishes, the system will automatically call the
Dispose method on the object.

Your use of each construct is independent of the use of the other one.

"Fred Chateau" <fc******@127.0.0.1> wrote in message
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom

Nov 15 '05 #2
Hi,
you can test a example like this:
the block it may throw a exception to client,when you use using,it may not
handle it and release related resources.but try/catch/finally will handle
and release revant resource success.try it yourself may can understand it .

--
---------ÌÕ×æºé(Ñ©ÔÆÓ¥)------------
MSN:xueyunying@hotmailcom
http://shanquan.blogone.net
Mail:ta***@gentle.com.cn
·ÖÏí֪ʶ£¬¹²´´¼¤Ç飬¹²Í¬³É¾Í
Share Knowledge,Share Vision,Share
Success
"Fred Chateau" <fc******@127.0.0.1> дÈëÓʼþ
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom

Nov 15 '05 #3
using (MyResource res = new MyResource())
{
DoSomething(res);
}

if strictly equivalent to:

{
MyResource res = new MyResource();
try
{
DoSomething(res);
}
finally
{
res.Dispose();
}
}

So, my advice is to use the first form rather than the second one. If you do
this, there should be little use for finally, because most of the situations
where you need a finally block should be related to resource disposal and
coded with "using" rather than finally.

Bruno.

"Fred Chateau" <fc******@127.0.0.1> a écrit dans le message de
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom

Nov 15 '05 #4

Hi Fred,

Thanks for posting in this group.
I think Peter's post has tell the main purpose and difference of Finally
and Using.
You still should use "try" and "catch" blocks to handle the exceptions in
your program.
For more details, please refer to the MSDN document:
http://msdn.microsoft.com/library/de...us/cpguide/htm
l/cpconusingfinallyblock.asp
http://msdn.microsoft.com/library/de...us/csspec/html
/vclrfcsharpspec_8_13.asp
http://msdn.microsoft.com/library/de...us/cpguide/htm
l/cpconusingtrycatchblocktocatchexceptions.asp

Hope this helps,

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #5
Ñ©ÔÆÓ¥ <go*********@hotmail.com> wrote:
you can test a example like this:
the block it may throw a exception to client,when you use using,it may not
handle it and release related resources.


Yes it will, because that's the whole point of the "using" construct -
it acts as an elegant way of writing a try/finally pair.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Peter Rilling <pe***@nospam.rilling.net> wrote:
I believe they have no relation to each other.


Yes they do. In particular, the C# language specification says that:

<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>

You can certainly use each construct within the other, but they're not
unrelated. "using" is just a quick way of doing a try/finally pair of
blocks.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
Hi Jon,

You 're right but the code given by the C# specs is a bit misleading:

* The "if (r1 != null)" test is useless because r1 is never null (if "new
R()" fails, it throws an exception but does not return null).

* The try/finally version lacks curly braces around the whole block, to get
the same scoping as the "using" statement on the r1 variable.

Bruno.
"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de
news:MP************************@msnews.microsoft.c om...
Peter Rilling <pe***@nospam.rilling.net> wrote:
I believe they have no relation to each other.


Yes they do. In particular, the C# language specification says that:

<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>

You can certainly use each construct within the other, but they're not
unrelated. "using" is just a quick way of doing a try/finally pair of
blocks.

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

Nov 15 '05 #8
Bruno Jouhier [MVP] <bj******@club-internet.fr> wrote:
You 're right but the code given by the C# specs is a bit misleading:

* The "if (r1 != null)" test is useless because r1 is never null (if "new
R()" fails, it throws an exception but does not return null).
Indeed. On the other hand, a different way of acquiring the resource
*may* return null instead of throwing an exception, in which case no
call to Dispose is made. For instance:

using System;

public class Test : IDisposable
{
static void Main()
{
using (Test t = new Test())
{
Console.WriteLine ("Got one");
}

using (Test t = GiveMeNull())
{
Console.WriteLine ("Not got one");
}
}

static Test GiveMeNull()
{
return null;
}

public void Dispose()
{
Console.WriteLine ("Disposing");
}
}

It would have been better if the example code in the language
specification had included an example of acquiring resources other than
with a constructor.
* The try/finally version lacks curly braces around the whole block, to get
the same scoping as the "using" statement on the r1 variable.


True. This appears to be an actual bug in the spec.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #9
> I believe they have no relation to each other.
i believe he was talking about
using(x)
{
}
in which case there is a relation.

--
Regards,
Alvin Bruney
Got tidbits? Get it here...
http://tinyurl.com/2bz4t
"Peter Rilling" <pe***@nospam.rilling.net> wrote in message
news:ex*************@TK2MSFTNGP11.phx.gbl...
I believe they have no relation to each other.

"finally" is used to ensure that code gets executed regardless of whether an exception occurred or not in a try/catch block. A using statement is just a shortcut for way of initializing variables that rely on the Dispose method. When the "using" block finishes, the system will automatically call the
Dispose method on the object.

Your use of each construct is independent of the use of the other one.

"Fred Chateau" <fc******@127.0.0.1> wrote in message
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks

within
a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom


Nov 15 '05 #10
""Jeffrey Tan[MSFT]"" wrote...
I think Peter's post has tell the main purpose and difference of Finally and Using. You still should use "try" and "catch" blocks to handle the exceptions in

your program.

Well, at least after reading this thread, I don't feel so stupid about
asking the question. It appears a little more complicated than I first
thought. :)

It sounds like working with "try" and "catch" blocks inside a "using"
statement might be a good way to code. Is it safe to assume that in all
Framework classes, Dispose will always call Close (if it exists) on a
resource before releasing it?

Also, on a related subject, I was reading the documentation today on the
System.Data.ODBC namespace and I noticed in the example of OdbcDataReader
that it says "always call Close when done reading". Aside from the poor
English, this can be confusing. :)

Is there a easy way to determine whether a resource "must" be closed
explicitly (as opposed to preferably)? Maybe the documentation should read:

// ... always call Close when done reading.
// Close the connection when done with it ... (This time we really, really
mean it!) ;)

Is there a simple way to determine which resources actually tie up native
resources and "must" be freed before going out of scope, short of sifting
through pages and pages of documentation? At first I thought maybe just
checking to see if a resource implements IDisposable would work, but I
notice DataReaders also implement that interface, so I guess it's not a good
indicator of what's really happening.

Thank you all for your help . . .

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom
Nov 15 '05 #11
""Jeffrey Tan[MSFT]"" wrote...
I think Peter's post has tell the main purpose and difference of Finally and Using. You still should use "try" and "catch" blocks to handle the exceptions in

your program.

Well, at least after reading this thread, I don't feel so stupid about
asking the question. It appears a little more complicated than I first
thought. :)

It sounds like working with "try" and "catch" blocks inside a "using"
statement might be a good way to code. Is it safe to assume that in all
Framework classes, Dispose will always call Close (if it exists) on a
resource before releasing it?

Also, on a related subject, I was reading the documentation today on the
System.Data.ODBC namespace and I noticed in the example of OdbcDataReader
that it says "always call Close when done reading". Aside from the poor
English, this can be confusing. :)

Is there a easy way to determine whether a resource "must" be closed
explicitly (as opposed to preferably)? Maybe the documentation should read:

// ... always call Close when done reading.
// Close the connection when done with it ... (This time we really, really
mean it!) ;)

Is there a simple way to determine which resources actually tie up native
resources and "must" be freed before going out of scope, short of sifting
through pages and pages of documentation? At first I thought maybe just
checking to see if a resource implements IDisposable would work, but I
notice DataReaders also implement that interface, so I guess it's not a good
indicator of what's really happening.

Thank you all for your help . . .

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom
Nov 15 '05 #12
One subtle difference between these two is, when using the finally block,
doing a Close/Dispose on a resource could throw an exception, while using
"using" will take care of the exception by itself.

One example to prove this is to open a File Stream to write to a floppy disk
and write more than the disk can hold. Since doing a close on the file
stream will flush the stream, it will throw an exception. So, now, there's
no way to get rid of the file stream. But when you use "using", the
internal file handle is closed properly (how?? I don't know).

-vJ

"Fred Chateau" <fc******@127.0.0.1> wrote in message
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom

Nov 15 '05 #13
One subtle difference between these two is, when using the finally block,
doing a Close/Dispose on a resource could throw an exception, while using
"using" will take care of the exception by itself.

One example to prove this is to open a File Stream to write to a floppy disk
and write more than the disk can hold. Since doing a close on the file
stream will flush the stream, it will throw an exception. So, now, there's
no way to get rid of the file stream. But when you use "using", the
internal file handle is closed properly (how?? I don't know).

-vJ

"Fred Chateau" <fc******@127.0.0.1> wrote in message
news:uZ**************@TK2MSFTNGP12.phx.gbl...
What are the differences between a "finally" and a "using" block?

Is it still necessary (or advisable) to use "try" and "catch" blocks within a "using" block?

--
Regards,

Fred Chateau
e-mail: fchateauAtHotelMotelNowDotCom

Nov 15 '05 #14
Fred Chateau <fc******@127.0.0.1> wrote:
Also, on a related subject, I was reading the documentation today on the
System.Data.ODBC namespace and I noticed in the example of OdbcDataReader
that it says "always call Close when done reading". Aside from the poor
English, this can be confusing. :)
I believe Close will just call Dispose anyway - that would be the
conventional behaviour, certainly, although I believe it should be
explicitly documented.
Is there a easy way to determine whether a resource "must" be closed
explicitly (as opposed to preferably)? Maybe the documentation should read:

// ... always call Close when done reading.
// Close the connection when done with it ... (This time we really, really
mean it!) ;)

Is there a simple way to determine which resources actually tie up native
resources and "must" be freed before going out of scope, short of sifting
through pages and pages of documentation? At first I thought maybe just
checking to see if a resource implements IDisposable would work, but I
notice DataReaders also implement that interface, so I guess it's not a good
indicator of what's really happening.


Seeing whether or not it implements IDisposable *is* the right way to
find out, IMO - just call Dispose (usually with a using statement) on
everything which implements it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #15

In general the null check is not useless because the body of the using
statement is free to assign to r1 at any time. However, the null tests will
not occur in the translation (and neither will the cast) if R is a struct.
HTH
Cheers
Jon Jagger
"Bruno Jouhier [MVP]" <bj******@club-internet.fr> wrote in message
news:Ok**************@TK2MSFTNGP10.phx.gbl...
Hi Jon,

You 're right but the code given by the C# specs is a bit misleading:

* The "if (r1 != null)" test is useless because r1 is never null (if "new
R()" fails, it throws an exception but does not return null).

* The try/finally version lacks curly braces around the whole block, to get the same scoping as the "using" statement on the r1 variable.

Bruno.
"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de
news:MP************************@msnews.microsoft.c om...
Peter Rilling <pe***@nospam.rilling.net> wrote:
I believe they have no relation to each other.


Yes they do. In particular, the C# language specification says that:

<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>

You can certainly use each construct within the other, but they're not
unrelated. "using" is just a quick way of doing a try/finally pair of
blocks.

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


Nov 15 '05 #16
Jon Jagger <jo*@jaggersoft.com> wrote:
In general the null check is not useless because the body of the using
statement is free to assign to r1 at any time.


No it's not - the local variable is read-only.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #17
You're right. (I dopped into Java momentarily. Please forgive me ;-)
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Jon Jagger <jo*@jaggersoft.com> wrote:
In general the null check is not useless because the body of the using
statement is free to assign to r1 at any time.


No it's not - the local variable is read-only.

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

Nov 15 '05 #18

Hi Fred,

I think Jon's post has answnered your question.
Do you still have any concern?
Please feel free to let me know.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #19

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

Similar topics

4
2936
by: Brian Alexander | last post by:
Hello; I'm curious to know how people preserve exceptions that arise in a try ... finally block. Consider this example: try: getResource() doSomething() finally: alwaysFreeResource()
16
10056
by: Bill | last post by:
Say I have a childThread currently is running a finally block to cleanup external resources. At the same time the main thread calls childThread.Abort(). The question is: when the...
10
1438
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()
16
2059
by: Chris | last post by:
Hi, regarding exception-handling : why put code in a 'finally' block, and not just after a 'catch'-block --> Example using 'finally ' : try { OpenFile();
16
2444
by: Chris | last post by:
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....
23
3038
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...
32
6083
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...
12
2646
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...
9
1943
by: TC | last post by:
Hey All, I posted this to the Crypto users group and forgot to add the VB.Net users group. I apologize for any confusion. I have been testing a try / catch / finally block and purposely...
0
7084
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
7278
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
7458
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
5578
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,...
1
5013
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1512
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 ...
1
736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.