In article <0a89c96d-de62-42ad-be48-6107ce10d...@googlegroups.com>, Frank B <fbick...@gmail.com> wrote:
> Ok; this is a bit esoteric. > > So finally is executed regardless of whether an exception occurs, so states > the docs. > > But, I thought, if I <return> from my function first, that should take > precedence. > > au contraire > > Turns out that if you do this: > > try: > failingthing() > except FailException: > return 0 > finally: > return 1 > > Then finally really is executed regardless... even though you told it to > return. > > That seems odd to me. That's exactly what it's supposed to do. The idea of finally is, "No matter what else happens, including calling sys.exit(), make sure this code executed". It's typically used to release some critical resource which was acquired in the body of the try block. https://docs.python.org/2/reference/compound_stmts.html#the-try-statement says: When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed on the way out.¹ The only way I can think of to bypass a finally block would be to call os._exit(), or send yourself a kill signal.
-- https://mail.python.org/mailman/listinfo/python-list