Thursday 23 September 2021

Python: Print exception stack trace

In this post, I am going to explain, couple of approaches to print exception stack trace in python.

 

Approach 1: Using ‘traceback.print_exception’ method.

 

Signature

traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)

Print exception information and stack trace entries from traceback object tb to file.

 

stack_trace_1.py

import traceback
import sys

def interest_calc(principal, time, rateOfIntrest):
    assert principal > 1
    assert time > 1 and time < 100
    assert rateOfIntrest > 1 and rateOfIntrest < 5

    return (principal * time * rateOfIntrest) / 1000

def demo(principal, time, rateOfIntrest):
    try:
        interest_calc(principal, time, rateOfIntrest)
    except AssertionError:
        traceback.print_exception(*sys.exc_info())

demo(0, 10, 5)


Output

Traceback (most recent call last):
  File "/Users/krishna/exceptions/stack_trace_1.py", line 13, in demo
    interest_calc(principal, time, rateOfIntrest)
  File "/Users/krishna/exceptions/stack_trace_1.py", line 5, in interest_calc
    assert principal > 1
AssertionError


Approach 2: Using 'traceback.print_exc' method.

 

Signature

traceback.print_exc(limit=None, file=None, chain=True)


This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).

 

stack_trace_2.py

import traceback
import sys

def interest_calc(principal, time, rateOfIntrest):
    assert principal > 1
    assert time > 1 and time < 100
    assert rateOfIntrest > 1 and rateOfIntrest < 5

    return (principal * time * rateOfIntrest) / 1000

def demo(principal, time, rateOfIntrest):
    try:
        interest_calc(principal, time, rateOfIntrest)
    except AssertionError:
        traceback.print_exc()

demo(0, 10, 5)


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment