特定模块的Python异常标题

时间:2013-11-07 23:47:17

标签: python

我有一个我正在使用的模块,它有自己的例外。有没有办法从该模块中捕获所有异常而不明确说明异常?

所以,假设我有一个名为foo的模块,它有错误foo.a foo.b ... foo.z 我该怎么做

try:
    method_from_foo() # throws a foo error
except any_foo_exception: # Can be any exception from the module foo
                          # if foo.a is thrown then it's caught here
                          # if foo.anything is thrown then it's caught here
    pass

而不是

try:
    method_from_foo() # throws a foo error
except foo.a, foo.b, ... foo.z:
    pass

我不想做一揽子Except,因为我想抓住与foo无关的所有其他例外

这可能吗?

2 个答案:

答案 0 :(得分:4)

通常通过为与模块相关的所有异常提供基本类型来实现此目的。因此,如果您有FancyFooBar模块,则可能需要先创建FancyFooBarException

class FancyFooBarException (Exeption):
    pass

然后你可以创建例外AB,......,并将它们基于:{/ p>

class AException (FancyFooBarException):
    pass

class BException (FancyFooBarException):
    pass

# ...

这样,抛出的所有异常都是相同的类型,FancyFooBarException,但仍然保留更具体的类型以实现更特殊的区分。所以你可以这样做:

try:
    fancyfoobar.someMethod()
except fancyfoobar.AException:
    print('AException!')
except fancyfoobar.FancyFooBarException:
    print('One of the other exceptions')
except Exception:
    Print('Any other exception.. we do not really want to catch this though')

答案 1 :(得分:0)

您可以为foo创建单个父异常,并让所有其他异常从中继承。然后,在您的try语句中,测试父类:

In [126]: class parentException(Exception):
   .....:     def __init__(self):
   .....:         self.value = "Parent Exception"
   .....:     def __str__(self):
   .....:         return repr(self.value)
   .....:     

In [127]: class child1Exception(parentException):
   .....:     def __init__(self):
   .....:         self.value = "Child 1 Exception"
   .....:         

In [128]: class child2Exception(parentException):
   .....:     def __init__(self):
   .....:         self.value = "Child 2 Exception"
   .....:             

In [129]: try:
   .....:     raise child1Exception
   .....: except parentError:
   .....:     print "Caught child1"
   .....:     
Caught child1