自定义异常列表。如何创建这样的列表?

时间:2014-08-15 13:51:03

标签: python exception exception-handling abort custom-exceptions

有没有办法在列表中存储用户定义的异常(我们的自定义异常)?因此,如果发生任何其他异常,这不在列表中......程序应该简单地中止。

2 个答案:

答案 0 :(得分:2)

单个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

答案 1 :(得分:2)

通常的方法是使用异常层次结构。

class OurError(Exception):
    pass

class PotatoError(OurError):
    pass

class SpamError(OurError):
    pass

# As many more as you like ...

然后你只是在except块中捕获OurError,而不是试图捕获它们的元组或具有多个除块之外的元组。


当然,没有什么能阻止你将它们存储在你提到的列表中:

>>> our_exceptions = [ValueError, TypeError]
>>> try:
...    1 + 'a'
... except tuple(our_exceptions) as the_error:
...    print 'caught {}'.format(the_error.__class__)
...     
caught <type 'exceptions.TypeError'>