About catching ANY exception

后端 未结 8 1172
一整个雨季
一整个雨季 2020-11-22 07:23

How can I write a try/except block that catches all exceptions?

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 07:49

    Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:

    import traceback
    import logging
    
    try:
        whatever()
    except Exception as e:
        logging.error(traceback.format_exc())
        # Logs the error appropriately. 
    

    You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

    The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

提交回复
热议问题