简体   繁体   中英

Why does a return statement in a finally block negates raise in the except block?

In my Python script I would like to catch an exception, perform some cleanup operations, and raise the exception again. Since the cleanup is common for both the success and failure paths, I tried putting it in the finally block. However, when I add a return statement inside the finally block, the raise is negated.

Here is an example (I am using Python 3.6.5):

def test():
    try:
        raise Exception('TEST')
    except:
        raise
    finally:
        print('FINALLY!')
        return ''

if __name__ == '__main__':
    test()
    print('SHOULD NOT REACH THIS LINE!')

Any idea why it is happening?

This is addressed directly in the docs .

On one side:

  • An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

BUT :

  • If the finally clause executes a break , continue or return statement, exceptions are not re-raised .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM