473,394 Members | 1,761 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,394 software developers and data experts.

purpose of 'finally' ?

Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->

Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris
Nov 16 '05 #1
16 2054
Any code in the finally block is guaranteed to be executed before the
routine exits. For example, what if another part of your code throws an
exception that you weren't expecting? What if the catch block doesn't
include the particular exception that is being thrown? In both of these
cases the finally block is always executed. So the purpose of the finally
block is really to tidy up, dispose etc. any variables used in the routine
before it exits.

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris

Nov 16 '05 #2

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

In your second example you have eaten the exception. Very bad.

If you had code after CloseFile() it would continue to execute and you would
not know that an exception occured.

And also you need to open the resource before the try block, since if it
fails in opening, you shouldn't try to close it.

Finally is not strictly necessary, but the equivilent constuct looks like

OpenFile();
try
{
UseFile();
}
catch (Exception exc)
{
CloseFile();
throw;
}

David
Nov 16 '05 #3
Hi,

The reasoning is that if an exception's thrown but not caught, you wouldn't
close your file. For example, your try block might call code that threw
exceptions not covered by the catch clause - in this case you'd get terrible
problems up the wazoo. Some languages don't have finally clauses (native C++
for example), and the alternative there is to encapsulate potentially shifty
code so that it's guaranteed to clean up after itself when it goes out of
scope, but generally finally's quite a nice way of ensuring reliable code
when it's one of two lines that could cause problems.

Steve

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris

Nov 16 '05 #4
Also, if your catch blocks throws an exception, the finally is still called.

Brad Williams
"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris

Nov 16 '05 #5
Finally always executes. If you don't use it, the line of code you reference
may never execute b/c it may never get hit.You are catching system.Exception
which is usually not recommended. Anyway, if you want to make sure it
happens, use a finally (which is highly recommended.) To that end, no, they
two blocks aren't necessarily the same b/c the exception block could throw
its own exception which wouldn't be caught and then the next line would
never be hit.

HTH,

Bill
"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris

Nov 16 '05 #6
Chris wrote:

<snip>

Have the relevant people considered adding this to the FAQ?
Nov 16 '05 #7
C# Learner <cs****@learner.here> wrote:
Chris wrote:

<snip>

Have the relevant people considered adding this to the FAQ?


Hadn't done - will do, if I remember :)

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

Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}


This isn't an interesting use of finally.

Here's some:

try
{
OpenFile();
if (fileEnd)
{
return;
}
// do work
}
finally
{
CloseFile();
}

try
{
OpenFile();

}
catch(SpecializedException se)
{
return se.ReturnCode;
}
finally
{
CloseFile();
}

I've got more!

--
Reginald Blue
"I have always wished that my computer would be as easy to use as my
telephone. My wish has come true. I no longer know how to use my
telephone."
- Bjarne Stroustrup (originator of C++) [quoted at the 2003
International Conference on Intelligent User Interfaces]
Nov 16 '05 #9
Chris.... If you are married, this code is self explanatory:

try
{
OpenToiletLid();
Flush();
}
catch(OverflowException e)
{
CallPlumber();
}
finally
{
CloseToiletLid();
}

http://www.geocities.com/jeff_louie/OOP/oop5.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #10
At many instances, like when you need to close an open database
connection

sqlConn.Close()

after having opened it before a Try block, you need the finally block.

For instance,

sqlConn.Open();
try
{
SqlDReader=sqlCmd.ExecuteReader();
}
catch (e as Exception)
{

}
finally
{
sqlConn.Close();
}

In the above code snippet, the try block may succeed or not. If it
succeeds, then the connection should be closed in the try block itself.
But you cannot be sure that it will succeed and if it does not, then you
need to close the connection in the catch block but then, the read
statement may also succeed!

So, ony the finally block allows you to accomplish the act of closing
the connection in the above scenario i.e., regardless of whether the try
succeeds or not, the open connection needs to be closed which can happen
with the finally block.

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #11
The purpose of a 'finally' block is to guarantee execution in case of either
an non-exception or exception condition. In your example, let's assume that
a file error happens. Control is transferred to the catch block, runs to the
end of the block and then goes into the finally block. At the completion of
the finally block execution returns to the next higher level.

A better example would be:
void Something
{
try
{
}
catch
{
}
finally
{
}
more code.
}

If no error, then try runs to completion, transfers to finally and then on
to 'more code'.
If error, then catch's code runs, finally runs and then return from the end
of the finally.
Note: There can't be any code between the end of catch and the start of
finally.
===========
Richard Lewis Haggard

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a 'catch'-block -->
Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris

Nov 16 '05 #12
I think using try...catch...finally is pointless. Or I use try...catch, or
try...finally. Anders Hejlsberg said on an interview that he put
try...catch...finally together 'cos some developers asked him, but he didn't
see any advantage on this

"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:eV**************@TK2MSFTNGP09.phx.gbl...
The purpose of a 'finally' block is to guarantee execution in case of either an non-exception or exception condition. In your example, let's assume that a file error happens. Control is transferred to the catch block, runs to the end of the block and then goes into the finally block. At the completion of the finally block execution returns to the next higher level.

A better example would be:
void Something
{
try
{
}
catch
{
}
finally
{
}
more code.
}

If no error, then try runs to completion, transfers to finally and then on
to 'more code'.
If error, then catch's code runs, finally runs and then return from the end of the finally.
Note: There can't be any code between the end of catch and the start of
finally.
===========
Richard Lewis Haggard

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a

'catch'-block -->

Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris


Nov 16 '05 #13
It's not pointless; the value depends on what the code is doing. Presenting
it as a single construct has several advantages, one being that the scope of
the affected region of code is easy to see.

In terms of IL a try-catch-finally is actually implemented in terms of a
try-catch nested inside a try-finally.

"Galore" <ga****@ig.com.br> wrote in message
news:OH**************@TK2MSFTNGP10.phx.gbl...
I think using try...catch...finally is pointless. Or I use try...catch, or
try...finally. Anders Hejlsberg said on an interview that he put
try...catch...finally together 'cos some developers asked him, but he didn't see any advantage on this

"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:eV**************@TK2MSFTNGP09.phx.gbl...
The purpose of a 'finally' block is to guarantee execution in case of

either
an non-exception or exception condition. In your example, let's assume

that
a file error happens. Control is transferred to the catch block, runs to

the
end of the block and then goes into the finally block. At the completion

of
the finally block execution returns to the next higher level.

A better example would be:
void Something
{
try
{
}
catch
{
}
finally
{
}
more code.
}

If no error, then try runs to completion, transfers to finally and then on to 'more code'.
If error, then catch's code runs, finally runs and then return from the

end
of the finally.
Note: There can't be any code between the end of catch and the start of
finally.
===========
Richard Lewis Haggard

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a

'catch'-block -->

Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris



Nov 16 '05 #14
Most of the time finally is uncalled for. Sometimes it makes sense. Take the
example of opening a file and then trying to write to it but generating an
exception. If the file isn't closed, then the environment leaks a file
handle plus the file itself is not available elsewhere. Without the finally
case, the file close code would have to be duplicated.
======
Richard Lewis Haggard

"Galore" <ga****@ig.com.br> wrote in message
news:OH**************@TK2MSFTNGP10.phx.gbl...
I think using try...catch...finally is pointless. Or I use try...catch, or
try...finally. Anders Hejlsberg said on an interview that he put
try...catch...finally together 'cos some developers asked him, but he didn't see any advantage on this

"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:eV**************@TK2MSFTNGP09.phx.gbl...
The purpose of a 'finally' block is to guarantee execution in case of

either
an non-exception or exception condition. In your example, let's assume

that
a file error happens. Control is transferred to the catch block, runs to

the
end of the block and then goes into the finally block. At the completion

of
the finally block execution returns to the next higher level.

A better example would be:
void Something
{
try
{
}
catch
{
}
finally
{
}
more code.
}

If no error, then try runs to completion, transfers to finally and then on to 'more code'.
If error, then catch's code runs, finally runs and then return from the

end
of the finally.
Note: There can't be any code between the end of catch and the start of
finally.
===========
Richard Lewis Haggard

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
Hi,

regarding exception-handling :
why put code in a 'finally' block, and not just after a

'catch'-block -->

Example using 'finally ' :

try
{
OpenFile();
}
catch (Exception exc)
{ ... }
finally
{
// Code put here to make sure that file will be closed
// regardless of whether we have a exception or not
CloseFile();
}

Example NOT using 'finally ' :
try
{
OpenFile();
}
catch (Exception exc)
{ ... }
CloseFile();

We have the same effect, no ?
Why use 'finally' at all ?

Thnx

Chris



Nov 16 '05 #15

"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:eu**************@TK2MSFTNGP11.phx.gbl...
Most of the time finally is uncalled for. Sometimes it makes sense. Take the example of opening a file and then trying to write to it but generating an
exception. If the file isn't closed, then the environment leaks a file
handle plus the file itself is not available elsewhere. Without the finally case, the file close code would have to be duplicated.
======
Richard Lewis Haggard

And how about the Thread.Abort call -- using the finally construct in the
thread method is the ONLY way to do cleanup.

regards
roy fine
"Galore" <ga****@ig.com.br> wrote in message
news:OH**************@TK2MSFTNGP10.phx.gbl...
I think using try...catch...finally is pointless. Or I use try...catch, or
try...finally. Anders Hejlsberg said on an interview that he put
try...catch...finally together 'cos some developers asked him, but he didn't
see any advantage on this

"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in message
news:eV**************@TK2MSFTNGP09.phx.gbl...
The purpose of a 'finally' block is to guarantee execution in case of

either
an non-exception or exception condition. In your example, let's assume

that
a file error happens. Control is transferred to the catch block, runs to
the
end of the block and then goes into the finally block. At the
completion of
the finally block execution returns to the next higher level.

A better example would be:
void Something
{
try
{
}
catch
{
}
finally
{
}
more code.
}

If no error, then try runs to completion, transfers to finally and
then on to 'more code'.
If error, then catch's code runs, finally runs and then return from

the end
of the finally.
Note: There can't be any code between the end of catch and the start

of finally.
===========
Richard Lewis Haggard

"Chris" <ch********@pandora.be> wrote in message
news:fZ********************@phobos.telenet-ops.be...
> Hi,
>
> regarding exception-handling :
> why put code in a 'finally' block, and not just after a
'catch'-block -->
>
> Example using 'finally ' :
>
> try
> {
> OpenFile();
> }
> catch (Exception exc)
> { ... }
> finally
> {
> // Code put here to make sure that file will be closed
> // regardless of whether we have a exception or not
> CloseFile();
> }
>
> Example NOT using 'finally ' :
> try
> {
> OpenFile();
> }
> catch (Exception exc)
> { ... }
> CloseFile();
>
> We have the same effect, no ?
> Why use 'finally' at all ?
>
> Thnx
>
> Chris
>
>



Nov 16 '05 #16
"Richard Lewis Haggard" <HaggardAtWorldDotStdDotCom> wrote in
news:eu**************@TK2MSFTNGP11.phx.gbl:
Most of the time finally is uncalled for. Sometimes it makes sense. Take
the example of opening a file and then trying to write to it but


In .NET its less needed than in unmanaged environments, but its still quite
essential unless you use using, which is essentially a try..finally.
or try...finally. Anders Hejlsberg said on an interview that he put
try...catch...finally together 'cos some developers asked him, but he
see any advantage on this


Its probably the same thing he said in Delphi when the Delphi guys always
asked him for it. Its not that he didnt see any advantage of a finally WITH a
catch, he didnt see the advantage of a:

try
catch
finally

vs

try
try
catch
finally

The Delphi guys asked him for years - and his answer was always that he didnt
see a big difference between the two. Thats very likely he was referring to
the same.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Get your ASP.NET in gear with IntraWeb!
http://www.atozed.com/IntraWeb/
Nov 16 '05 #17

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

Similar topics

4
by: Dado | last post by:
I lost the point: What is purpose of putting objects to null: If I make a class, JFrame for example, with button which start connection dialog, which is class with connection and statement...
4
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()
26
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise...
8
by: Ron Stephens | last post by:
Can anyone give me a brief comparison of the purposes of these two projects (AnyGUI and pyGUI)? In other words, how are the motivations and goals for each project different? Ron Stephens
16
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...
3
by: Brian | last post by:
Is it possible to have more than one try/catch/finally block within a method? Also, if the code never enters the try block of code, is the finally block executed? I have a try block in a branch...
8
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block?...
4
by: hazz | last post by:
I just haven't been able to get a solid feel for the purpose of what appears to be a declarative statement just above the class below. Anyone with a clear explanation that will finally stick with...
27
by: jm | last post by:
I am having trouble understanding the purposes of an interface, even though the concept of interfaces is around me all the time (user interface, for example). I'm just not understanding software...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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...

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.