Mortezaipo Mortezaipo - 1 month ago 8
Python Question

How to get python exception traceback in function

I have a function which should handle all errors:

def err(e):
import traceback
message = traceback.print_exc()
print(message)

if __name__ == "__main__":
try:
1/0 # just sample
except Exception as e:
err(e)


But it returns a short error like so:

integer division or modulo by zero


But I need more details (
traceback
) to check errors.

Answer

You're passing the exception to your function so why use traceback, you've got e there; just grab e.__traceback__ if you need the traceback:

import traceback

def err(e):   
    tb = e.__traceback__
    # print traceback
    traceback.print_tb(tb)

For an option that doesn't depend on dunders, you could use sys.exc_info and keep the traceback:

import traceback, sys

def err(e):
    *_, tb = sys.exc_info()    
    # print traceback
    traceback.print_tb(tb)
Comments