mortymacs
mortymacs

Reputation: 3746

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.

Upvotes: 0

Views: 947

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

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)

Upvotes: 1

Syuqri
Syuqri

Reputation: 84

According to the python documentation:

traceback.print_exc([limit[, file]])

This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file). (In fact, it uses

sys.exc_info() to retrieve the same information in a thread-safe way instead of using the deprecated variables.)

What you're essentially doing is just printing out the error message that is being produced by 1/0

If you want to print out a personalized error message you could do the following:

if __name__ == "__main__":
    try:
        1/0 # just sample
    except Exception as e:
        print 'This is the error I am expecting'

Upvotes: 0

Related Questions