例如:
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 :(
我需要从其他所有未知的异常中过滤出一种特殊的异常(已知)。我还需要断言来继续相同的异常处理,
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# Handle Assertion Errors here
# But I want the except below to happen too!
except:
# Handle everything here
我将添加一个真实的例子来更简洁地传达这个想法:
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!"
答案 0 :(得分:5)
try:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# handle assertion
raise
except Exception:
# handle everything
我假设你不能将抛出不同异常的两个语句分开(例如,因为它们在另一个函数中一起关闭)。如果可以的话,以下内容更加精确和直接:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
try:
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# handle assertion
raise
except Exception:
# handle everything
它更精确,因为如果FruitFunction()
引发的未知异常恰好是AssertionError
,那么它就不会被内部try
捕获。在不分离语句的情况下,没有(合理的)方法来区分从两个不同位置抛出的两个相同类型的异常。因此,对于第一个代码,您最好希望FruitFunction()
不会引发AssertionError
,或者如果它发生,那么它可以像处理另一个代码一样处理。
答案 1 :(得分:3)
try:
# Do something
myurl = urllib.urlopen(parametes)
assert myurl.status == 202
except Exception as e:
# Handle Exception
print('An error occured')
if isinstance(e, AssertionError):
# Handle AssertionError
print('it was something serious too!')
else:
# proceed normal stuff
答案 2 :(得分:0)
如果它既引发了一个未知异常又引发了AssertionError
,并且您需要同时处理它们,则应该使用两个单独的try语句。
try:
raise IndexError()
assert 'orange' in myfruits
except AssertionError:
print 'AssertionError'
except:
print 'another error'
以上只会捕捉第一个错误,而
try:
raise IndexError()
except:
print 'another error'
try:
assert 'orange' in myfruits
except AssertionError:
print 'AssertionError'
将捕获这两个错误。