Search code examples
pythonpython-multithreadingtry-catch-finallytry-finally

finally statement doesn't take effect in a thread


According to the official python documentation, "finally" statement will always be executed, and thus is usually used for clean-up operations.

If "finally" is present, it specifies a ‘cleanup’ handler. The "try" clause is executed, including any "except" and "else" clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The "finally" clause is executed. If there is a saved exception, it is re-raised at the end of the "finally" clause. If the "finally" clause raises another exception or executes a return or break statement, the saved exception is discarded:

However, when I implemented the "try-finally" statement in a thread, "finally" part seems not being executed.

from __future__ import print_function
import threading
def thread1():
    try:
        while True:
            pass
    except:
        print("exception")
    finally:
        print("closed")

t = threading.Thread(target = thread1)
t.setDaemon(True)
t.start()
while True:
    pass

When interrupted by ctrl-c, "closed" is not printed on the screen. Why is that?

While in following code "finally" does work (no surprise)

from __future__ import print_function
try:
    while True:
       pass
finally:
    print("closed")

Solution

  • In the documentation for the thread module (which underlies threading):

    When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors.