Handle Arbitrary Exception, Print Default Exception Message

前端 未结 5 644
我寻月下人不归
我寻月下人不归 2021-01-01 16:00

I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 16:33

    Consider using the Python logging module, this is will give you a lot of the functionality to log problems for later inspection. Below is a simple example of using the logging module to to log exceptions:

    import logging
    LOG_FILE = '/tmp/exceptions.log'
    logging.basicConfig(filename=LOG_FILE,level=logging.ERROR)
    
    while True:
    try:
        # Code that may throw exceptions
    except Exception, e:
        logging.exception("An exception happened")
    

    By using the logging.exception function within an exception handler as is done here the Exception info is automatically added to the logging message.

提交回复
热议问题