13

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?

1
  • Have you tried creating a thread that throws an exception? Commented Nov 22, 2012 at 13:26

2 Answers 2

12

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.

1
  • I am using concurrent thread pool. If a thread got killed a new thread will spawn in thread pool or not??? Commented Jun 21, 2017 at 16:06
7

From the threading documentation:

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

And also:

join(timeout=None)

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception –, or until the optional timeout occurs.

In other words, the uncaught exception is a way to end a thread, and will be detected in the parent's join call on said thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.