处理python中的特定异常类型 [英] Handle specific exception type in python

查看:169
本文介绍了处理python中的特定异常类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些处理异常的代码,我只想做特定的代码,只有当它是一个特定的异常,只有在调试模式下。所以例如:

  try:
stuff()
除了例外为e:
如果_debug和e是KeyboardInterrupt:
sys.exit()
logging.exception(正常处理)

因此,我不想只添加一个:

 除了KeyboardInterrupt:
sys.exit()

因为我试图保持这个调试代码的差异最小

解决方案

嗯,真的,你可能应该保持 KeyboardInterrupt 分离。为什么你只想在调试模式下处理键盘中断,否则会吞下它们?



可以使用 isinstance 检查对象的类型:

  try:
stuff()
except Exception作为e:
如果_debug和isinstance(e,KeyboardInterrupt):
sys.exit()
logger.exception(正常处理)


I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example:

try:
    stuff()
except Exception as e:
    if _debug and e is KeyboardInterrupt:
        sys.exit()
    logging.exception("Normal handling")

As such, I don't want to just add a:

except KeyboardInterrupt:
    sys.exit()

because I'm trying to keep the difference in this debug code minimal

解决方案

Well, really, you probably should keep the handler for KeyboardInterrupt separated. Why would you only want to handle keyboard interrupts in debug mode, but swallow them otherwise?

That said, you can use isinstance to check the type of an object:

try:
    stuff()
except Exception as e:
    if _debug and isinstance(e, KeyboardInterrupt):
        sys.exit()
    logger.exception("Normal handling")

这篇关于处理python中的特定异常类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆