Handle specific exception type in python

淺唱寂寞╮ 提交于 2019-12-06 17:11:50

问题


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


回答1:


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



回答2:


This is pretty much the way it's done.

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

There's minimal repetition. Not zero, however, but minimal.

If the "normal handling" is more than one line of code, you can define a function to avoid repetition of the two lines of code.




回答3:


You should let KeyboardInterrupt bubble all the way up and trap it at the highest level.

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit()
    except:
        pass

def main():
    try:
        stuff()
    except Exception as e:
        logging.exception("Normal handling")
        if _debug:
            raise e



回答4:


What's wrong with

try:
    stuff()
except KeyboardInterrupt:
    if _debug:
        logging.exception("Debug handling")
        sys.exit()
    else:
        logging.exception("Normal handling")



回答5:


You can name specific exceptions in Python:

try:
    stuff()
except KeyboardInterrupt:
    sys.exit()
except Exception:
    normal_handling()



回答6:


Either use the standard method mentioned in the other answers, or if you really want to test within the except block then you can use isinstance().

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



回答7:


try:
    stuff()
except KeyboardInterrupt:
    if _debug:
        sys.exit()
    logging.exception("Normal handling")
except ValueError:
    if _debug:
        sys.exit()
    logging.exception("Value error Normal handling")
else:
    logging.info("One more message without exception")


来源:https://stackoverflow.com/questions/4329453/handle-specific-exception-type-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!