SoFunction
Updated on 2025-03-02

python3 traceback module to track and print exception information

In Python 3, you can use thetracebackModule to track and print exception information. This module provides many functions to handle exceptions and can output stack information of exceptions to help you locate the errors. Here is a simple example code that demonstrates how to use ittracebackModule to track error reports:

print_exc print exception

import traceback

def function_a():
    return 1 / 0  # Trigger an exception for zero deletion
def main_function():
    try:
        function_a()
    except Exception as e:
        # Print exception information        traceback.print_exc()

main_function()

In the above example, we define two functionsfunction_aandmain_function. existfunction_aIn   we deliberately triggered a zero-dividing exception. existmain_function, we usetry...exceptStructure to catch exceptions and calltraceback.print_exc()To print the exception information.

When you run this code, you will see output containing exception information and stack trace.

extract_tb extract stack

traceback.extract_tb()The function is used to extract stack trace information and return a list containing information of each frame. Each frame information is returned as a tuple, including file name, line number, function name, and source code line. Here is a simple example code that demonstrates how to use ittraceback.extract_tb()Function:

import traceback

def function_a():
    return 1 / 0  # Trigger an exception for zero deletion
def main_function():
    try:
        function_a()
    except Exception as e:
        # Extract stack trace information        tb_list = traceback.extract_tb(e.__traceback__)
        
        # Print information for each frame        for tb in tb_list:
            print("File:", )
            print("Line:", )
            print("Function:", )
            print("Code:", )
            print()

main_function()

In the above example, we define two functionsfunction_aandmain_function,infunction_aA zero-deletion exception was deliberately triggered. existmain_function, we usetry...exceptStructure captures exceptions and passestraceback.extract_tb(e.__traceback__)Extract stack trace information.

Then, we traverse the extracted stack trace information list.tb_list, and print the file name, line number, function name, and source code line for each frame.

When you run this code, you will see that the output contains detailed information for each frame.

This is the article about python3 traceback module tracking and printing exception information. This is the end of this article. For more related python3 traceback printing exception information, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!