try/except/finally
Roy Smith
roy at panix.com
Fri Jun 6 13:39:31 EDT 2014
More information about the Python-list mailing list
Fri Jun 6 13:39:31 EDT 2014
- Previous message (by thread): try/except/finally
- Next message (by thread): try/except/finally
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
In article <0a89c96d-de62-42ad-be48-6107ce10d215 at googlegroups.com>, Frank B <fbicknel at 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.
- Previous message (by thread): try/except/finally
- Next message (by thread): try/except/finally
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list