Handle specific exception type in python

后端 未结 7 1655
一向
一向 2021-02-07 02:24

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:
         


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 03:08

    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")
    

提交回复
热议问题