473,568 Members | 2,939 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: fchateauAtHotel MotelNowDotCom
Nov 15 '05 #1
18 1805
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******** ******@TK2MSFTN GP12.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: fchateauAtHotel MotelNowDotCom

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***@gent le.com.cn
·ÖÏí֪ʶ£¬¹²´´¼ ¤Ç飬¹²Í¬³É¾Í
Share Knowledge,Share Vision,Share
Success
"Fred Chateau" <fc******@127.0 .0.1> дÈëÓʼþ
news:uZ******** ******@TK2MSFTN GP12.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: fchateauAtHotel MotelNowDotCom

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******** ******@TK2MSFTN GP12.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: fchateauAtHotel MotelNowDotCom

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/cpconusingfinal lyblock.asp
http://msdn.microsoft.com/library/de...us/csspec/html
/vclrfcsharpspec _8_13.asp
http://msdn.microsoft.com/library/de...us/cpguide/htm
l/cpconusingtryca tchblocktocatch exceptions.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*********@ho tmail.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Peter Rilling <pe***@nospam.r illing.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)r 1).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.co m>
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.co m> a écrit dans le message de
news:MP******** *************** *@msnews.micros oft.com...
Peter Rilling <pe***@nospam.r illing.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)r 1).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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #8
Bruno Jouhier [MVP] <bj******@clu b-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.WriteLi ne ("Got one");
}

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

static Test GiveMeNull()
{
return null;
}

public void Dispose()
{
Console.WriteLi ne ("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.co m>
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.r illing.net> wrote in message
news:ex******** *****@TK2MSFTNG P11.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******** ******@TK2MSFTN GP12.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: fchateauAtHotel MotelNowDotCom


Nov 15 '05 #10

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

Similar topics

4
2942
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
10065
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 ThreadAbortException is thrown, does the childThread finish the remaining code in the finally block?
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()
16
2072
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
2453
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. dr.close(); works fine in the try but not in the finally.
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...
32
6100
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.
12
2664
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...
9
1944
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 raising exceptions and I've noticed that if an exception of "Length of the data to decrypt is invalid." is raised with the CryptoStream object, later...
0
7693
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
7604
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...
0
7916
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
7962
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
6275
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...
1
5498
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1207
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.