例如:
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!"
最佳答案
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
,或者如果是,则可以像处理另一个一样处理它。
关于python - 如何区分同一try语句中发生的不同异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20362916/