【发布时间】:2014-08-15 13:51:02
【问题描述】:
有什么方法可以将用户定义的异常(我们自定义的异常)存储在列表中?因此,如果发生任何其他不在列表中的异常.. 程序应该简单地中止。
【问题讨论】:
标签: python exception exception-handling abort custom-exceptions
有什么方法可以将用户定义的异常(我们自定义的异常)存储在列表中?因此,如果发生任何其他不在列表中的异常.. 程序应该简单地中止。
【问题讨论】:
标签: python exception exception-handling abort custom-exceptions
单个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'>
【讨论】:
except: 块和 sys.exit() 或其他任何内容