[Python-Dev] Fwd: try...else

Thomas Wouters thomas@xs4all.net
Thu, 28 Dec 2000 21:21:15 +0100


On Thu, Dec 28, 2000 at 03:45:49PM +0100, M.-A. Lemburg wrote:

> > I had expected that in try: except: else
> > the else clause always got executed, but it seems not for return

> I think Robin mixed up try...finally with try...except...else.
> The finally clause is executed even in case an exception occurred.

(MAL and I already discussed this in private mail: Robin did mean
try/except/else, and 'finally' already executes when returning directly from
the 'try' block, even in Python 1.5)

> He does have a point however that 'return' will bypass 
> try...else and try...finally clauses. I don't think we can change
> that behaviour, though, as it would break code.

This code:

try:
   return
except:
   pass
else:
   print "returning"

will indeed not print 'returning', but I believe it's by design. I'm against
changing it, in any case, and not just because it'd break code :) If you
want something that always executes, use a 'finally'. Or don't return from
the 'try', but return in the 'else' clause. 

The 'except' clause is documented to execute if a matching exception occurs,
and 'else' if no exception occurs. Maybe the intent of the 'else' clause
would be clearer if it was documented to 'execute if the try: clause
finishes without an exception being raised' ? The 'else' clause isn't
executed when you 'break' or (after applying my continue-in-try patch ;)
'continue' out of the 'try', either.

Robin... Did I already reply this, on python-list or to you directly ? I
distinctly remember writing that post, but I'm not sure if it arrived. Maybe
I didn't send it after all, or maybe something on mail.python.org is
detaining it ?

-- 
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!