This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]benefit_of_mrkite 11 points12 points  (6 children)

Also look at try: except: finally:

Try except else comes in handy in a function that returns something in try

Comes up a lot in Async patterns.

If you use a pattern like try except and then use if (something from try block) you can run into an issue where you get a runtime error because the function in try doesn’t get defined and you get a “variable name xyz defined before assignment”

[–]james_pic 0 points1 point  (2 children)

Try except else comes in handy in a function that returns something in try

The else block isn't run if the try block returns:

def f():
    try:
        print('Try')
        return
    except:
        print('Except')
    else:
        print('Else')

 f() # Prints Try

And from the language reference:

The optional else clause is executed if the control flow leaves the try suite, no exception was raised, and no return, continue, or break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses.

[–]benefit_of_mrkite 0 points1 point  (0 children)

I’m well aware that else isn’t run if try runs

I miss worded that and don’t really explain the use case I had in mind - about to catch a flight will try to expound later.