How to print exception stack trace in Python?

10 Jul, 2020
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=None, file=None, chain=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 moduleimport traceback  # declaring and assigning arrayA = [1, 2, 3, 4]  # exception handlingtry:    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 handledprint("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(etype, value, tb, limit=None, file=None, chain=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 librariesimport tracebackimport sys  # initialising variablesa = 4b = 0  # exception handlingtry:    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 handledprint("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

Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts