Python处理多个异常

7

我希望以特定方式处理某个异常,并一般性地记录所有其他异常。以下是我的代码:

class MyCustomException(Exception): pass


try:
    something()
except MyCustomException:
    something_custom()
except Exception as e:
    #all others
    logging.error("{}".format(e))

问题在于即使是MyCustomException也会被记录,因为它继承自Exception。我该如何避免这种情况?

如果在 something() 中引发了一个 MyCustomException,那么这段代码就能正常工作。你是如何在 something() 中引发异常的? - Henrik Andersson
2个回答

8

你的代码还有什么其他问题吗?

MyCustomException 应该在流程到达第二个 except 子句之前被检查和处理。

In [1]: def test():
   ...:     try:
   ...:         raise ValueError()
   ...:     except ValueError:
   ...:         print('valueerror')
   ...:     except Exception:
   ...:         print('exception')
   ...:         

In [2]: test()
valueerror

In [3]: issubclass(ValueError,Exception)
Out[3]: True

6

只有第一个匹配的except块将被执行:

class X(Exception): pass

try:
    raise X
except X:
    print 1
except Exception:
    print 2

只会输出1。

即使在except块中引发异常,也不会被其他的except块捕获:

class X(Exception): pass

try:
    raise X
except X:
    print 1
    0/0
except Exception:
    print 2

输出1并引发ZeroDivisionError: integer division or modulo by zero异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接