Handle specific exception type in python

后端 未结 7 1649
一向
一向 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条回答
  •  伪装坚强ぢ
    2021-02-07 02:56

    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.

提交回复
热议问题