是否有任何方法可以将用户定义的异常(我们自定义的异常)存储在列表中?因此,如果发生任何其他异常,它不在列表中…程序应该直接中止。
单个except
可以有多个错误,自定义或其他:
>>> class MyError(Exception):
pass
>>> try:
int("foo") # will raise ValueError
except (MyError, ValueError):
print "Thought this might happen"
except Exception:
print "Didn't think that would happen"
Thought this might happen
>>> try:
1 / 0 # will raise ZeroDivisionError
except (MyError, ValueError):
print "Thought this might happen"
except Exception:
print "Didn't think that would happen"
Didn't think that would happen
通常的方法是使用异常层次结构。
class OurError(Exception):
pass
class PotatoError(OurError):
pass
class SpamError(OurError):
pass
# As many more as you like ...
那么你就在except块中捕获OurError
,而不是试图捕获它们的元组或具有多个except块。
当然,实际上没有什么可以阻止您将它们存储在您提到的列表中:
>>> our_exceptions = [ValueError, TypeError]
>>> try:
... 1 + 'a'
... except tuple(our_exceptions) as the_error:
... print 'caught {}'.format(the_error.__class__)
...
caught <type 'exceptions.TypeError'>