Python一个例外的多个处理程序

时间:2015-04-26 09:42:01

标签: python exception coding-style paradigms

我想这样做:

try:
    raise A()
except A:
    print 'A'
except (A, B):
    print 'A,B'

我希望打印AA,B

这不起作用(只执行第一个except)。第一个except吞下错误是有意义的,如果你想在它的父级之前捕获一个子类。

但还有另一种优雅的方法可以让它发挥作用吗?

我当然可以执行以下操作,但这似乎是多余的代码重复,尤其是如果涉及的不仅仅是AB

try:
    raise A()
except A:
    print 'A'
    print 'A,B'
except B:
    print 'A,B'

(与Multiple exception handlers for the same Exception相关但不重复。用法不同,我想知道如何以最少的代码重复来处理它。)

2 个答案:

答案 0 :(得分:1)

捕获可能的异常并在以后从实例中获取异常类型是相当常见的:

try:
    raise A()
except (A, B) as e:
    if isinstance(e, A):
        print('A')
    print('A', 'B')

另一种选择是从另一个类继承一个类,例如

class B(Exception):
    def do(self):
        print('A', 'B')

class A(B, Exception):
    def do(self):
        print('A')
        super().do()

然后

try:
    raise B()
except (A, B) as e:
    e.do()

将打印A B

try:
    raise A()
except (A, B) as e:
    e.do()

将打印AA B

答案 1 :(得分:-1)

您可以使用嵌套的try-except-blocks:

try:
    try:
        raise A()
    except A:
        print 'A'
        raise
except (A, B):
    print 'A,B'
相关问题