When an exception is raised inside a thread without catching it anywhere else, will it then kill the whole application/interpreter/process? Or will it only kill the thread?
An exception thrown in a spawned worker thread will cause this thread to be silently terminated if the exception is unhandled. You need to make sure all exceptions are handled in all threads. If an exception happens in this new thread, you want to handle it and be notified of its occurrence.
In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.
Let's try it:
import threading
import time
class ThreadWorker(threading.Thread):
def run(self):
print "Statement from a thread!"
raise Dead
class Main:
def __init__(self):
print "initializing the thread"
t = ThreadWorker()
t.start()
time.sleep(2)
print "Did it work?"
class Dead(Exception): pass
Main()
The code above yields the following results:
> initializing the thread > Statement from a thread! > Exception in thread > Thread-1: Traceback (most recent call last): File > "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner > self.run() File ".\pythreading.py", line 8, in run > raise Dead Dead > ----- here the interpreter sleeps for 2 seconds ----- > Did it work?
So, the answer to your question is that a raised Exception crashes only the thread it is in, not the whole program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With