线程内未捕获的异常是否只会杀死线程或整个进程?

tap*_*per 12 python multithreading exception

当一个异常在一个线程内引发但没有在其他任何地方捕获它时,它会杀死整个应用程序/解释器/进程吗?或者它只会杀死线程?

Bo *_*ich 12

我们来试试吧:

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()
Run Code Online (Sandbox Code Playgroud)

上面的代码产生以下结果:

> 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?
Run Code Online (Sandbox Code Playgroud)

所以,你的问题的答案是,一个引发的Exception只会崩溃它所在的线程,而不是整个程序.


Eli*_*sky 6

线程文档:

一旦线程的活动开始,线程就被认为是"活着的".当run()方法终止时,它会停止活动 - 通常,或者通过引发未处理的异常.is_alive()方法测试线程是否处于活动状态.

并且:

加入(超时=无)

等到线程终止.这会阻塞调用线程,直到调用join()方法的线程终止 - 正常或通过未处理的异常 - 或者直到发生可选的超时.

换句话说,未捕获的异常是一种结束线程的方法,并且将在父join线程中对所述线程的调用中检测到.