Open In App

How to print exception stack trace in Python?

Last Updated : 10 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Python Traceback

To print stack trace for an exception the suspicious code will be kept in the try block and except block will be employed to handle the exception generated. Here we will be printing the stack trace to handle the exception generated. The printing stack trace for an exception helps in understanding the error and what went wrong with the code. Not just this, the stack trace also shows where the error occurred.

The general structure of a stack trace for an exception: 

  • Traceback for the most recent call.
  • Location of the program.
  • Line in the program where the error was encountered.
  • Name of the error: relevant information about the exception
     

Example: 

Traceback (most recent call last):
  File "C:/Python27/hdg.py", line 5, in 
    value=A[5]
IndexError: list index out of range

Method 1: By using print_exc() method.

This method prints exception information and stack trace entries from traceback object tb to file.

Syntax: traceback.print_exc(limit=Nonefile=Nonechain=True)

Parameters: This method accepts the following parameters:

  • if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
  • If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
  • If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.

Return: None.

Code:

Python3




# import module
import traceback
  
# declaring and assigning array
A = [1, 2, 3, 4]
  
# exception handling
try:
    value = A[5]
      
except:
    # printing stack trace
    traceback.print_exc()
  
# out of try-except
# this statement is to show
# that program continues normally
# after an exception is handled
print("end of program")


Output: 

Traceback (most recent call last):
  File "C:/Python27/hdg.py", line 8, in 
    value=A[5]
IndexError: list index out of range
end of program

Method 2: By using print_exception() method.

This method prints exception information and stack trace entries from traceback object tb to file.

Syntax : traceback.print_exception(etypevaluetblimit=Nonefile=Nonechain=True)

Parameters: This method accepts the following parameters:

  • if tb argument 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) argument 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.
  • if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
  • If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
  • If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.

Return: None.

Code:

Python3




# import required libraries
import traceback
import sys
  
# initialising variables
a = 4
b = 0
  
# exception handling
try:
    value = a / b
  
except:
    # printing stack trace
    traceback.print_exception(*sys.exc_info())
  
# out of try-except
# this statement is to show 
# that program continues
# normally after an exception is handled
print("end of program")


Output: 

Traceback (most recent call last):
  File "C:/Python27/hdg.py", line 10, in 
    value=a/b
ZeroDivisionError: integer division or modulo by zero
end of program


Similar Reads

Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
Python | Numpy matrix.trace()
With the help of Numpy matrix.trace() method, we can find the sum of all the elements of diagonal of a matrix by using the matrix.trace() method. Syntax : matrix.trace() Return : Return sum of a diagonal elements of a matrix Example #1 : In this example we can see that by using matrix.trace() method can help us to find the sum of all the elements o
1 min read
Numpy recarray.trace() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
2 min read
Plotly - How to show legend in single-trace scatterplot with plotly express?
In this article let's see how to show legend in single-trace scatterplot with plotly express. A 'trace' is the name given to each plot inside the chart. Generally in plotly legend is not visible for single trace scatter plots. Example: In the below, example packages and data are imported and a single trace scatter plot is plotted using px.scatter()
1 min read
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
Python Print Exception
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. In this article, we are going to focus on 'How can we print an exception in Py
5 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python | Reraise the Last Exception and Issue Warning
Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. def example(): try: int('N/A') except ValueError: print("Didn't work") raise example() Output : Didn't work Traceback (most recent call last): File "", line 1, in File "", line 3, in example ValueError: invalid litera
2 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice.
2 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg