Does 'finally' always execute in Python?

前端 未结 6 2062
眼角桃花
眼角桃花 2021-01-29 21:38

For any possible try-finally block in Python, is it guaranteed that the finally block will always be executed?

For example, let’s say I return while in an <

6条回答
  •  北海茫月
    2021-01-29 22:32

    Yes. Finally always wins.

    The only way to defeat it is to halt execution before finally: gets a chance to execute (e.g. crash the interpreter, turn off your computer, suspend a generator forever).

    I imagine there are other scenarios I haven't thought of.

    Here are a couple more you may not have thought about:

    def foo():
        # finally always wins
        try:
            return 1
        finally:
            return 2
    
    def bar():
        # even if he has to eat an unhandled exception, finally wins
        try:
            raise Exception('boom')
        finally:
            return 'no boom'
    

    Depending on how you quit the interpreter, sometimes you can "cancel" finally, but not like this:

    >>> import sys
    >>> try:
    ...     sys.exit()
    ... finally:
    ...     print('finally wins!')
    ... 
    finally wins!
    $
    

    Using the precarious os._exit (this falls under "crash the interpreter" in my opinion):

    >>> import os
    >>> try:
    ...     os._exit(1)
    ... finally:
    ...     print('finally!')
    ... 
    $
    

    I'm currently running this code, to test if finally will still execute after the heat death of the universe:

    try:
        while True:
           sleep(1)
    finally:
        print('done')
    

    However, I'm still waiting on the result, so check back here later.

提交回复
热议问题