java timer异常_在上下文管理器中捕获由threading.Timer引发的异常

我写了一个简单的 TimeManager :一个上下文管理器,在输入上下文时触发 threading.Timer ,并在退出时取消它 . 如果计时器在退出上下文之前关闭,则会引发异常:

import threading

class TimeManager(object):

def __init__(self):

self._timeout = 1

def _timeoutHandler(self):

raise Exception("Timeout!")

def __enter__(self):

self.timer = threading.Timer(self._timeout, self._timeoutHandler)

self.timer.start()

return self

def __exit__(self, exc_type, exc_val, exc_tb):

self.timer.cancel()

return False

显然我无法在主线程中捕获异常,因为它属于一个单独的线程:

>>> with TimeManager() as t:

... try:

... time.sleep(5)

... except Exception:

... print "caught"

...

Exception in thread Thread-3:

Traceback (most recent call last):

File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner

self.run()

File "/usr/lib64/python2.6/threading.py", line 736, in run

self.function(*self.args, **self.kwargs)

File "", line 5, in _timeoutHandler

Exception: Timeout!

那么,我怎样才能在主线程中捕获异常?我应该放弃上下文管理器的想法吗?

注意问题与here描述的问题不同,那里没有涉及多个线程 . 我认为它也与this不同,其中消息传递会否定超时的目的 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值