Python printing exception stack trace

Traceback in Python

Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when an exception occurs. Since a traceback gives all the information regarding the exception it becomes easier to track one and fix it.

General structure of a stack trace for an exception:

Traceback for most recent call Location of the program Line in the program where error was encountered Name of the error: relevant information about the exception
Traceback (most recent call last): File "C:/Python27/hdg.py", line 5, in value = A[5] IndexError: list index out of range

The module uses traceback objects, this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info() .

Functions in the Module

  • traceback.print_tb(tb, limit = None, file = None) : If limit is positive it prints upto limit stack trace entries from traceback object tb. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output.
  • traceback.print_exception(etype, value, tb, limit = None, file = None, chain = True) : Prints exception information and stack trace entries from traceback object tb to file. If tb is not None, it prints a header Traceback (most recent call last): . It prints the exception etype and value after the stack trace. If type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
  • traceback.print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).
  • traceback.print_last(limit = None, file = None, chain = True) : It works only after an exception has reached an interactive prompt. This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain).
  • traceback.print_stack(f = None, limit = None, file = None) : If limit is positive, prints up to limit stack trace. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start.
  • traceback.extract_tb(tb, limit = None) : Returns a StackSummary object representing a list of “pre-processed” stack trace entries (FrameSummary object containing attributes filename, lineno, name, and line) extracted from the traceback object tb. It is useful for alternate formatting of stack traces.
  • traceback.extract_stack(f = None, limit = None) : Extracts the raw traceback from the current stack frame. The return value has the same format as for extract_tb().
  • traceback.format_list(extracted_list) : Given a list of tuples or FrameSummary objects returns a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well.
  • traceback.format_exception_only(etype, value) : Formats the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. It returns a list of strings each ending in a new line.
  • traceback.format_exception(etype, value, tb, limit = None, chain = True) : Formats stack trace and exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). It returns a list of strings each ending in new line and some have internal newlines too. When these lines are concatenated and printed they generate an exactly same output as print_exception().
  • traceback.format_exc(limit = None, chain = True) : This is like print_exc(limit) except it returns a string instead of printing to a file.
  • traceback.format_tb(tb, limit = None) : shorthand for format_list(extract_tb(tb, limit)).
  • traceback.format_stack(f = None, limit = None) : shorthand for format_list(extract_stack(f, limit)).
  • traceback.clear_frames(tb) : Clears the local variables of all stack frames in a traceback tb by calling clear() method of each frame object.
  • traceback.walk_stack(f) : Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract().
  • traceback.walk_tb(tb) : Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract().
Читайте также:  Html img margin auto

Example : Program that prints the exception stack trace.

Источник

Python Program to Print Stack Trace

Python Certification Course: Master the essentials

A stack trace , also known as stack traceback , traceback, or backtrace, prints all the function calls that took place before an error occurred. Python Print Stack Trace assists users in figuring out the cause of an error and solving it.

What is Stack Trace in Python?

A stack trace is used to display all the function calls before an error occurs. The error is reported on the final line of the stack trace. The stack trace also shows information and function calls related to the thrown error to help users locate and solve it.

How to Print Stack Trace in Python?

Method 1: Using print_exc()

In the following code snippet, the value of the denominator is set to 0 to view how Python print stack trace works. The traceback.print_exc() method in the except block prints the program’s location, the line where the error was encountered, and the name and relevant information about the error. The last line confirms that the entire code executes without hindrance.

Method 2: Using print_exception()

In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. The last line printed confirms that the entire code executes successfully.

More Examples for Understanding

Example 1

In the following erroneous code snippet, blood_group is written as bloodgroup to see how Python print stack trace works. The displayed stack trace contains information about the type of error — NameError, that occurred because the referenced variable bloodgroup is not defined. The exception tells us that the variable, function, or class does not exist due to incorrect reference.

Example 2

In the following code snippet, the value for children is set to 0 to view how Python print stack trace works. The displayed stack trace contains information about the type of error — ZeroDivisionError, that occurred because the denominator is 0 .

Example 3

In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. This example is used to add more depth to the stack for easy visualization. Initially the function h() is called followed by g() and finally f() where trying to address index 5 throws an error.

FAQs

Q: Which module is required for Python print stack trace?

A: Importing the traceback module helps to extract, format and print stack traces.

Q: What does a stack trace show?

A: A stack trace displays the call stack (set of active method calls) and provides information about the methods called before an error occurs. It helps developers to figure out what went wrong in the code.

Q: What information does the stack trace contain? The stack trace contains :

  • Traceback for the most recent call.
  • Location of the program.
  • Erroneous Line.
  • Type of error and relevant information.

Q: What is the difference between print_exc and print_exception?

print_exc print_exception
traceback.print_exc(limit=None, file=None, chain=True) traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
It accepts 3 parameters limit , file , and chain . It accepts 6 parameters etype , value , tb , limit , file , chain

Conclusion

  • In Python print stack trace to see the function calls that took place before an error occurred.
  • The stack trace information helps to locate and fix the error easily.
  • The traceback module in Python provides functionalities to deal with the stack trace.
  • The methods used to print stack trace are print_exception() and print_exc() .

Источник

Оцените статью