[Python-Dev] Fwd: try...else
Tim Peters
tim.one@home.com
Thu, 28 Dec 2000 23:25:44 -0500
[Fred, suggested doc change near the end]
[Thomas Wouters]
> (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)
>
> 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.
Guido's out of town again, so I'll channel him: Thomas is correct on all
counts. In try/else, the "else" clause should execute if and only if
control "falls off the end" of the "try" block.
IOW, consider:
try:
arbitrary stuff
x = 1
An "else" clause added to that "try" should execute when and only when the
code as written executes the "x = 1" after the block. When "arbitrary
stuff" == "return", control does not fall off the end, so "else" shouldn't
trigger. Same thing if "arbitrary stuff" == "break" and we're inside a
loop, or "continue" after Thomas's patch gets accepted.
> The 'except' clause is documented to execute if a matching
> exception occurs, and 'else' if no exception occurs.
Yup, and that's imprecise: the same words are used to describe (part of)
when 'finally' executes, but they weren't intended to be the same.
> 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' ?
Sorry, I don't find that any clearer. Let's be explicit:
The optional 'else' clause is executed when the 'try' clause
terminates by any means other than an exception or executing a
'return', 'continue' or 'break' statement. Exceptions in the
'else' clause are not handled by the preceding 'except' clauses.
> The 'else' clause isn't executed when you 'break' or (after
> applying my continue-in-try patch ;) 'continue' out of the
> 'try', either.
Hey, now you're channeling me <wink>! Be afraid -- be very afraid.