在Python中处理特定异常类型
我有一些代码用来处理错误(异常),我想在特定情况下做一些特别的事情,比如只在调试模式下才做。举个例子:
try:
stuff()
except Exception as e:
if _debug and e is KeyboardInterrupt:
sys.exit()
logging.exception("Normal handling")
所以,我不想简单地加一个:
except KeyboardInterrupt:
sys.exit()
因为我想尽量让这个调试代码的变化保持最小。
7 个回答
1
你可以选择使用其他回答中提到的标准方法,或者如果你真的想在异常处理的代码块中进行测试,那么你可以使用 isinstance() 这个函数。
try:
stuff()
except Exception as e:
if _debug and isinstance(e, KeyboardInterrupt):
sys.exit()
logging.exception("Normal handling")
21
这基本上就是处理这个问题的方法。
try:
stuff()
except KeyboardInterrupt:
if _debug:
sys.exit()
logging.exception("Normal handling")
except Exception as e:
logging.exception("Normal handling")
这里的重复很少,虽然不是完全没有,但确实很少。
如果“正常处理”的代码超过一行,你可以定义一个函数,这样就可以避免重复写那两行代码。
37
其实,你应该把处理KeyboardInterrupt
的部分单独放在一起。为什么你只想在调试模式下处理键盘中断,而在其他情况下就不管它呢?
不过,你可以用isinstance
来检查一个对象的类型:
try:
stuff()
except Exception as e:
if _debug and isinstance(e, KeyboardInterrupt):
sys.exit()
logger.exception("Normal handling")