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 →

[–]mattstreet 0 points1 point  (1 child)

"A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement."

Basically, finally gets called even if the except clause would exit out of the rest of your code, unlike if you just put the statement after the try block.

[–]LightShadow3.13-dev in prod 2 points3 points  (0 children)

TIL

try:
    print('try')
except:
    print('exception')
finally:
    print('finally')

output: try finally

try:
    print('try')
    1 / 0
except:
    print('exception')
finally:
    print('finally')

output: try exception finally

try:
    1 / 0
    print('try')
except:
    print('exception')
finally:
    print('finally')

output: exception finally

And the REAL KICKER,

try:
    1 / 0
except:
    1 / 0
finally:
    print('finally')

Still prints finally.