说我有这个代码:
def wait_for_x(timeout_at=None):
while condition_that_could_raise_exceptions
if timeout_at is not None and time.time() > timeout_at:
raise SOMEEXCEPTIONHERE
do_some_stuff()
try:
foo()
wait_for_x(timeout_at=time.time() + 10)
bar()
except SOMEEXCEPTIONHERE:
# report timeout, move on to something else
Run Code Online (Sandbox Code Playgroud)
如何SOMEEXCEPTIONHERE为函数选择异常类型?为该函数创建唯一的异常类型是否合理,以便不存在condition_that_could_raise_exceptions引发相同异常类型的危险?
wait_for_x.Timeout = type('Timeout', (Exception,), {})
Run Code Online (Sandbox Code Playgroud)
是的,只要没有合适的内置异常类型,您当然应该定义自己的异常类。在某些情况下(例如,如果您在 LXML 或 BeautifulSoup 之上构建某种 HTML munger),使用其他模块的异常也可能是合适的。