在python中处理特定的异常类型

Fal*_*rri 17 python exception-handling exception

我有一些处理异常的代码,我想做一些特定的事情,只要它是一个特定的异常,并且只在调试模式下.例如:

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

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

except KeyboardInterrupt:
    sys.exit()
Run Code Online (Sandbox Code Playgroud)

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

mip*_*adi 22

嗯,真的,你可能应该把处理程序KeyboardInterrupt分开.为什么你只想在调试模式下处理键盘中断,否则吞下它们呢?

也就是说,您可以isinstance用来检查对象的类型:

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


S.L*_*ott 20

这几乎就是它的完成方式.

try:
    stuff()
except KeyboardInterrupt:
    if _debug:
        sys.exit()
    logging.exception("Normal handling")
except Exception as e:
    logging.exception("Normal handling")
Run Code Online (Sandbox Code Playgroud)

重复次数最少.然而,不是零,而是最小的.

如果"正常处理"不止一行代码,您可以定义一个函数以避免重复两行代码.

  • @marcog:`除了异常,因为e`在Python 2.6+中有效. (5认同)