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

try...finally is more powerful than I thought.

def res():
try:
a = 1
return
finally:
print "do I get here?"

res()

outputs "do I get here?"

I can't say why I didn't really expect this, the control flow is a
little wierd as the function isn't really returning at the "return"
statement but executing the bit in the finally: block and then
returning. I think :)

That being said, I like it a lot. How is this working internally? Does
the finally get executed when try code block goes out of scope? This
would happen during a return or an exception which could explain the magic.

Brian

Jul 18 '05 #1
12 2448
Brian Kelley wrote:

def res():
try:
a = 1
return
finally:
print "do I get here?"

res()

outputs "do I get here?"

I can't say why I didn't really expect this, the control flow is a
little wierd as the function isn't really returning at the "return"
statement but executing the bit in the finally: block and then
returning. I think :)


These results might also be of interest:
def res(): .... try:
.... return 1
.... finally:
.... return 2
.... res() 2 def res(): .... try:
.... return 1
.... finally:
.... return
.... res()
def res(): .... try:
.... return 1
.... finally:
.... pass
.... res()

1

-Peter
Jul 18 '05 #2
>> def res():
try:
a = 1
return
finally:
print "do I get here?"

res()

outputs "do I get here?"
These results might also be of interest:
def res(): ... try:
... return 1
... finally:
... return 2
... res() 2 def res(): ... try:
... return 1
... finally:
... return
... res()
def res(): ... try:
... return 1
... finally:
... pass
... res() 1


def res(): .... print 1
.... try:
.... print 2
.... return 3
.... print 4
.... finally:
.... print 5
.... res()

1
2
5
3
interesting.

Jul 18 '05 #3
Lee Harr wrote:
def res(): ... print 1
... try:
... print 2
... return 3
... print 4
... finally:
... print 5
... res()

1
2
5
3

interesting.


Why? It just proves that "finally" works, and
executes when the return statement is encountered.

(The point of my examples was to show that finally can
actually override the value that would otherwise have been
returned. I thought that was interesting, but unfortunately
I'm not sure what your example adds to the previous two posts.
Maybe I'm just missing the point...)

-Peter
Jul 18 '05 #4

Jython once had a bug where it would not execute the outer finally
through a return, ie. in:

def x():
try:
try:
return 1
finally:
doSomething1()
finally:
doSomething2()

doSomething2() would not get executed.
The workaround was straightforward: save the return value in some local
variable and return at the end.

In case you like such puzzles, this is the test code:

http://cvs.sourceforge.net/viewcvs.p....2&view=markup

Btw. CPython never failed a single test case in there.

Have fun,
Ype
email at xs4all.nl
Jul 18 '05 #5
Brian Kelley <bk*****@wi.mit.edu> writes:
def res():
try:
a = 1
return
finally:
print "do I get here?"

res()

outputs "do I get here?"

I can't say why I didn't really expect this, the control flow is a
little wierd as the function isn't really returning at the "return"
statement but executing the bit in the finally: block and then
returning. I think :)

That being said, I like it a lot. How is this working internally?
Does the finally get executed when try code block goes out of scope?
This would happen during a return or an exception which could explain
the magic.


Internally, and locally to one function, leaving via returning a value
and raising an exception is pretty similar.

Cheers,
mwh

--
I'm not sure that the ability to create routing diagrams
similar to pretzels with mad cow disease is actually a
marketable skill. -- Steve Levin
-- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html
Jul 18 '05 #6
[Brian Kelley]
How is [try..finally] working internally? Does
the finally get executed when try code block goes out of scope? This
would happen during a return or an exception which could explain the
magic.


From the Python Language Reference

http://www.python.org/doc/current/ref/try.html

"""
The try...finally form specifies a `cleanup' handler. The try clause
is executed. When no exception occurs, the finally clause is executed.
When an exception occurs in the try clause, the exception is
temporarily saved, the finally clause is executed, and then the saved
exception is re-raised. If the finally clause raises another exception
or executes a return or break statement, the saved exception is lost.
A continue statement is illegal in the finally clause. (The reason is
a problem with the current implementation - this restriction may be
lifted in the future). The exception information is not available to
the program during execution of the finally clause.
"""

The Language Reference is very readable, not excessively formal, and
well worth a read.

http://www.python.org/doc/current/ref/ref.html

regards,

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #7
Alan Kennedy wrote:
When an exception occurs in the try clause, the exception is
temporarily saved, the finally clause is executed, and then the saved
exception is re-raised.


I've always wondered, how does one use this in real life?
Since I cannot write try... except... finally..., which would be the
most intuitive construct to me, I understand I should write
try:
try:
...
finally:
...
except:
...

to achieve the same effect.

Am I right? I.e. (again) how do you people use try .. finally in real
use cases?

Does anyone else think Python could have a nicer syntax for this one?

Mauro

Jul 18 '05 #8
Mauro Cicognini wrote:

I've always wondered, how does one use this in real life?
Since I cannot write try... except... finally..., which would be the
most intuitive construct to me, I understand I should write
try:
try:
...
finally:
...
except:
...

to achieve the same effect.

Am I right? I.e. (again) how do you people use try .. finally in real
use cases?
I use the above in the exceptionally rare case where I really want
that particular behaviour: cleanup prior to unrelated exception handling.

Normally what I want is cleanup, leaving exception handling to the calling
code, in which case I just need a finally.

More often I want exception handling, and don't need cleanup, so of course
just the except clause will do.

And only slightly more often than the first case, but much less often
than the other two, I want exception handling but an overall cleanup,
in which case I use the above nested format but with the finally on
the outside and the except on the inside.
Does anyone else think Python could have a nicer syntax for this one?


Perhaps, but it's such an incredibly insignificant thing as far as
I'm concerned that after hearing of the existence of lengthy past
discussions about this, and the near certainty it will not be changed,
I stopped wasting my time worrying about it and went back to writing
code that worked, and some that didn't :-).

(Basically, check the archives for the reasons this is the way it is.)

-Peter
Jul 18 '05 #9

"Mauro Cicognini" <mc******@siosistemi.it> wrote in message news:bo**********@grillo.cs.interbusiness.it...

<,,,>
try:
try:
...
finally:
...
except:
...

to achieve the same effect.

Am I right? I.e. (again) how do you people use try .. finally in real
use cases?

Does anyone else think Python could have a nicer syntax for this one?
That's probably why they called it begin...rescue in Ruby :)
G-:

Mauro

Jul 18 '05 #10
On 2003-11-07, Peter Hansen <pe***@engcorp.com> wrote:
Lee Harr wrote:
>>> def res():

... print 1
... try:
... print 2
... return 3
... print 4
... finally:
... print 5
...
>>> res()

1
2
5
3

interesting.


Why? It just proves that "finally" works, and
executes when the return statement is encountered.

(The point of my examples was to show that finally can
actually override the value that would otherwise have been
returned. I thought that was interesting, but unfortunately
I'm not sure what your example adds to the previous two posts.
Maybe I'm just missing the point...)

Yes. I just found the entire thread interesting. I know that
people who are unfamiliar with the try ... finally syntax can
easily fire up the interpreter and play around with it for
themselves, but I thought the "basic functionality" example
might make the rest of the thread more clear.

I have written a lot of python code and have never used finally.

Jul 18 '05 #11
Lee Harr wrote:

On 2003-11-07, Peter Hansen <pe***@engcorp.com> wrote:
Lee Harr wrote:
interesting.


Why? It just proves that "finally" works, and
executes when the return statement is encountered.


Yes. I just found the entire thread interesting. I know that
people who are unfamiliar with the try ... finally syntax can
easily fire up the interpreter and play around with it for
themselves, but I thought the "basic functionality" example
might make the rest of the thread more clear.

I have written a lot of python code and have never used finally.


Ah, good point. :-)

-Peter
Jul 18 '05 #12
Peter Hansen wrote:
Mauro Cicognini wrote:
Does anyone else think Python could have a nicer syntax for this one?


Perhaps, but it's such an incredibly insignificant thing as far as
I'm concerned that after hearing of the existence of lengthy past
discussions about this, and the near certainty it will not be changed,
I stopped wasting my time worrying about it and went back to writing
code that worked, and some that didn't :-).

(Basically, check the archives for the reasons this is the way it is.)


Thanx for the nice explanation.

I might check the archives... and yes, I agree it is a rather
insignificant thing, in fact I was just curious and the mention of past
wars does check out. I for no reason will ever wish to stir them up again.

BR,
Mauro

Jul 18 '05 #13

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

Similar topics

8
by: Will | last post by:
I just discovered Python and looked briefly at one of the tutorials for beginners... It looks a lot like the old Command line Basic... I'm sure it does much more but... 1 - Can you create...
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...
77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
54
by: Stefan Arentz | last post by:
I was just reading through some old articles in the 'Why not develop new language' thread and came across the finally debate. Everytime I mention 'finally' to C++ programmers I get almost...
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...
2
by: Ralph Krausse | last post by:
I created a try/catch/finally but when an expection is thrown, the catch does not handle it... (I know this code is wrong, I want to force the error for this example) try { DataSet ds = new...
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()
7
by: Sky | last post by:
I have been looking for a more powerful version of GetType(string) that will find the Type no matter what, and will work even if only supplied "{TypeName}", not the full "{TypeName},{AssemblyName}"...
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: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.