What is the traceback.print_tb() function in Python?

Overview

The traceback module in Python provides a standardized interface to extract, format, and print stacktraces.

The print_tb method of the traceback module prints the stacktraces from the traceback object up to a limit.

Syntax

Here’s the syntax for traceback.print_tb() method:

traceback.print_tb(tb, limit=None, file=None)

Parameters

Here are the parameters of the traceback.print_tb() method:

  • tb: This is the traceback object.
  • limit: This parameter can be used to specify the amount of trace required. The default value is None and will print the whole stacktrace. When limit is a negative value, the abs(limit) is taken into consideration.
  • file: This parameter indicates where the stacktrace output should be directed to. The default value is None and the output goes to the standard error.

Example

import traceback
def func_2():
print("hello educative")
raise Exception("")
def func_1():
func_2()
print("Printing complete stacktrace:")
try:
func_1()
except Exception as e:
traceback.print_tb(e.__traceback__)
print("-" * 8)
print("Printing upto 2 stacktraces:")
try:
func_1()
except Exception as e:
traceback.print_tb(e.__traceback__, limit=2)

Explanation

  • Line 1: We import the traceback module.
  • Lines 3–5: The func_2() function is defined where it throws an exception.
  • Lines 7–8: The func_1() function is defined. This invokes func_2().
  • Lines 11–14: func_1() is invoked, and the complete stacktrace is printed.
  • Lines 18–21: func_1() is invoked, and the stacktrace up to level 2 is printed. We do this using the limit parameter of the print_tb() function.

Copyright ©2024 Educative, Inc. All rights reserved