【发布时间】:2012-10-31 16:37:43
【问题描述】:
try:
content = my_function()
except:
exit('Could not complete request.')
我想修改上面的代码来检查content的值是否包含字符串。我想过使用if 'stuff' in content:或正则表达式,但我不知道如何将它放入try;所以如果匹配是False,它会引发异常。当然,我总是可以在该代码之后添加一个if,但是有没有办法把它挤进去?
伪代码:
try:
content = my_function()
if 'stuff' in content == False:
# cause the exception to be raised
except:
exit('Could not complete request.')
【问题讨论】:
-
是的,你可以。参考手册raising-exceptions
-
你不应该像这样捕获所有异常。它将隐藏所有语法和其他编程错误,调试将是一场噩梦。指定要捕获的异常类型(类)。
标签: python exception try-catch