473,804 Members | 3,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2490
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******@siosi stemi.it> wrote in message news:bo******** **@grillo.cs.in terbusiness.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

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

Similar topics

8
2293
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 windows, buttons, user input fields, etc as you can with Visual Basic? 2 - Can you call Windows Procedures or what ever they call them
26
2525
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 Error # Error is subclass of Exception
77
5391
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 the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
54
2912
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 emotional responses about why it is not needed in C++. I don't get that. For example, consider the following code. Please note, I can only use heap allocated objects in my current project (new/delete). //
23
3084
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 and datareader object ONLY if certain conditions are met. But, if I want to clean these up in the...
2
1941
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 DataSet(); string strID = ds.Tables.Rows.ToString(); }
26
2565
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
7821
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}" As far as I know yet -- hence this question -- there is no 'one solution fits all', but instead there are several parts that have to be put together to check. What I have so far is, and would like as much feedback as possible to ensure I've...
5
7148
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 different and perhaps more efficient way to use objects than try-catch-finally? ...
0
9704
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9569
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10069
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9130
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5503
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
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
2
3802
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.