yay*_*ayu 7 python exception-handling
我想以某种方式处理特定的异常,并且通常记录所有其他异常.这就是我所拥有的:
class MyCustomException(Exception): pass
try:
something()
except MyCustomException:
something_custom()
except Exception as e:
#all others
logging.error("{}".format(e))
Run Code Online (Sandbox Code Playgroud)
问题是甚至MyCustomException会被记录,因为它继承自Exception.我该怎么做才能避免这种情况?
你的代码还发生了什么?
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
Run Code Online (Sandbox Code Playgroud)
只会执行第一个匹配的除了块:
class X(Exception): pass
try:
raise X
except X:
print 1
except Exception:
print 2
Run Code Online (Sandbox Code Playgroud)
只打印1.
即使你在except块中引发异常,除了块之外,它不会被其他异常捕获:
class X(Exception): pass
try:
raise X
except X:
print 1
0/0
except Exception:
print 2
Run Code Online (Sandbox Code Playgroud)
打印1和加注 ZeroDivisionError: integer division or modulo by zero