Handle specific exception type in python

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

提交回复
热议问题