Handle specific exception type in python

后端 未结 7 1662
一向
一向 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:45

    You can name specific exceptions in Python:

    try:
        stuff()
    except KeyboardInterrupt:
        sys.exit()
    except Exception:
        normal_handling()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 02:58
    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")
    
    0 讨论(0)
  • 2021-02-07 03:05

    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
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2021-02-07 03:09

    What's wrong with

    try:
        stuff()
    except KeyboardInterrupt:
        if _debug:
            logging.exception("Debug handling")
            sys.exit()
        else:
            logging.exception("Normal handling")
    
    0 讨论(0)
提交回复
热议问题