12

他の場所でキャッチせずにスレッド内で例外が発生した場合、アプリケーション/インタープリター/プロセス全体を強制終了しますか? それとも、スレッドを殺すだけですか?

4

2 に答える 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.

于 2012-11-22T13:29:21.520 に答える
6

スレッドドキュメントから:

スレッドのアクティビティが開始されると、スレッドは「生きている」と見なされます。run()メソッドが終了すると、通常どおり、または未処理の例外を発生させることにより、動作を停止します。is_alive()メソッドは、スレッドが生きているかどうかをテストします。

そしてまた:

join(timeout = None)

スレッドが終了するまで待ちます。これにより、join()メソッドが呼び出されたスレッドが終了するまで(通常または未処理の例外によって)、またはオプションのタイムアウトが発生するまで、呼び出し元のスレッドがブロックされます。

言い換えると、キャッチされなかった例外はスレッドを終了する方法であり、そのスレッドでの親のjoin呼び出しで検出されます。

于 2012-11-22T13:34:52.873 に答える