Best Practices for Python Exception Handling

        The code snippet in this blog post was written a week ago, but has never been published. Because there are not many articles dedicated to Python exception handling, I don’t know if my own handling is a relatively good practice. I hope that people who see this blog post will actively make decisions, and share any excellent exception handling practices below. I will continue to update this blog post and keep track of new best practices as I encounter them.

1. It is absolutely impossible to simply ignore and hide caught exceptions.

    The following code is a negative example. Do not do this. It simply swallows the caught exception. This time, the follow-up work will bring a lot of trouble, which may prevent us from locating where the bug is.

try:
    do_something()
except:  #except Exception as e
    pass

Second, try to catch specific exceptions.

       Try to catch specific exceptions, which is also a requirement of PEP8. This is easy to do when writing your own code for the first time, but when cleaning up someone else's code it can become extremely painful. I've actually been looking for ways to deal with this situation, and I'll update the blog post later when I find better practices. There is a way to give this part to the guy who is more familiar with this part of the code. Hahaha

try:
    do_something()
except ValueError:
    do_exception_deal()

3. When you need to catch all exceptions, record the relevant stack trace information instead of just recording an error message.

    Some code may want to catch all exceptions, such as long-running code in the topmost loop. The following code provides a relatively good practice to use logging or this tarceback to log all stack information related to the exception.

#!/usr/bin/python3

import logging
import time
import traceback
import sys


logging.basicConfig(level=logging.INFO)



def log_traceback(ex):
    tb_lines = traceback.format_exception(ex.__class__, ex, ex.__traceback__)
    tb_text = ''.join(tb_lines)
    print(tb_text)


def get_number(arg):

    return int(arg)

try:
    get_number("hello")
except Exception as e:
    # logging.exception(e)  #使用logging模块的exception方法去打印tarceback
    log_traceback(e) #使用traceback模块去输出traceback。
    

for i in range(10):
    time.sleep(1)
    logging.info("hello")

Use # logging.exception(e) or log_traceback(e) to record all exception stack information, which is very helpful for later work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325453060&siteId=291194637