Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an in-thread uncaught exception kill only the thread or the whole process?

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?

like image 709
taper Avatar asked Nov 22 '12 13:11

taper


People also ask

What happens if exception is thrown in 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.

What are the limitations of threading in Python?

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.


1 Answers

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.

like image 124
Bo Milanovich Avatar answered Oct 12 '22 12:10

Bo Milanovich