如何根据Python 3中的字符串参数来捕获一般异常?
我正在与引发如下异常的API进行通信:raise Exception("end of time")
。如何根据Python 3中的字符串参数来捕获一般异常?
只有当字符串参数是“结束时间”时,我怎样才能捕获Exception
?
我不想做的事:
except Exception:
pass
我想要做的事,如:
except Exception("end of time"):
pass
然而,这并不能捕获异常。
例回溯:
File "test.py", line 250, in timeout_handler
raise Exception("end of time")
Exception: end of time
使用异常.args
过滤的东西,如果你需要的话:
try:
raise Exception("end of time")
except Exception as e:
if e.args[0] == 'end of time':
pass # handle
else:
raise
'str(e)'也很好。 –
@ Jean-FrançoisFabre如果len(e.args)> 1'怎么办? – user8615908
那么,理想的情况下应该是提高一个自定义异常。由于情况并非如此,所以解决方法可以检查异常消息。
except Exception as exp:
if str(exp) == 'end of time':
# do something
else:
# pass or do something else
消息属性仅在Python 2中可用。 –
@MosesKoledoye不知道。更新了我的答案。谢谢。 – hspandher
@vaultah重复问题的链接是不恰当的,因为答案不适用于Python 3. – user8615908
增加了另一个。希望mgilson会更新他的答案。 – vaultah