Handle specific exception type in python

后端 未结 7 1651
一向
一向 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 03:12

    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")
    
    0 讨论(0)
提交回复
热议问题