例如:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except:
# I don't know how to distinguish these two errors :(
我需要从所有未知的异常中筛选出一种特殊的异常(已知的)。我还需要断言来继续同样的异常处理
^{pr2}$为了更简洁地传达这一观点,我将添加一个真实的例子:
try:
# This causes all sorts of errors
myurl = urllib.urlopen(parametes)
# But if everything went well
assert myurl.status == 202
# proceed normal stuff
except:
# print "An error occured" if any error occured
# but if it was an assertion error,
# add "it was something serious too!"
我假设您不能将抛出不同异常的两个语句分开(例如,因为它们在另一个函数中一起关闭)。如果可以的话,以下内容将更加精确和直接:
^{pr2}$它更精确,因为如果
FruitFunction()
引发的未知异常恰好是AssertionError
,那么它就不会被捕获到内部try
。如果不分离语句,就没有(合理的)方法来区分从两个不同位置抛出的同一类型的两个异常。因此,对于第一个代码,您最好希望FruitFunction()
不会引发AssertionError
,或者如果它发生了,那么可以用与另一个相同的方式处理。在如果它同时引发了一个未知异常和一个
AssertionError
,并且您需要同时处理这两个问题,那么应该使用两个单独的try语句。在上面的方法只捕获第一个错误,而
^{pr2}$将捕获两个错误。在
相关问题 更多 >
编程相关推荐