【发布时间】:2013-04-05 13:14:11
【问题描述】:
有没有更好的方法来做这样的事情:
class SpecialError(Exception):
pass
try:
# Some code that might fail
a = float(a)
# Some condition I want to check
if a < 0:
raise SpecialError
except (ValueError, SpecialError):
# This code should be run if the code fails
# or the condition is not met
a = 999.
【问题讨论】:
-
不,有很多用例可以引发异常。不过,在这种情况下,我只会提出
ValueError,不需要自定义。 -
为什么不在进入区块前检查条件?
标签: python exception-handling try-catch