12

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

4

2 回答 2

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()

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

> 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?

因此,您的问题的答案是,引发的异常仅崩溃它所在的线程,而不是整个程序。

于 2012-11-22T13:29:21.520 回答
6

线程文档:

一旦线程的活动开始,线程就被认为是“活动的”。当它的 run() 方法终止时,它会停止活动——无论是正常终止,还是引发未处理的异常。is_alive() 方法测试线程是否处于活动状态。

并且:

加入(超时=无)

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

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

于 2012-11-22T13:34:52.873 回答