线程计时器函数中引发的捕获异常

时间:2018-12-13 08:15:29

标签: python timer exception-handling

我创建了一个threading.Timer,并给他分配了一个函数timed_func(),该函数将在时间到时执行。在timed_func()中,我提出了一个我想捕获的异常。但是我似乎找不到方法。

以下是一些示例代码:

from threading import Timer

def timed_func():
    print "In timed_func."
    raise Exception

if __name__=="__main__":

    timer = Timer(3, timed_func)

    try:
        timer.start()
        print "Timer started."
    except Exception:
        print "Exception catched"

目前,这只会产生以下错误,即未捕获到异常:

λ python exception_sandbox.py
Timer started.
In timed_func.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Program Files\Miniconda2\lib\threading.py", line 801, in 
__bootstrap_inner
    self.run()
  File "C:\Program Files\Miniconda2\lib\threading.py", line 1073, in run
    self.function(*self.args, **self.kwargs)
  File "exception_sandbox.py", line 5, in timed_func
    raise Exception
Exception

0 个答案:

没有答案