variable
variable

Reputation: 9736

Can we get stack trace from an exception?

To get stacktrace, I use:

except:
    import traceback
    print(traceback.format_exec())

Can I get stacktrace from an exception without using traceback? Example:

except Exception as e:
    print(e)
    print(e.traceback) #is there command like this?

Upvotes: 0

Views: 149

Answers (3)

dsvp9xyjsqmfvi8p
dsvp9xyjsqmfvi8p

Reputation: 152

Without using the traceback module, we should be able to get some further detail using sys.exc_info. This returns a tuple including traceback info:

try:
    ...
except Exception as e:
    tb = sys.exec_info()[2]
    ...

The traceback object has info about the stack frame and line number the error occurred on.

This is what traceback uses under the hood.

Upvotes: 2

Ryan Gaudion
Ryan Gaudion

Reputation: 987

Use the Traceback Module - More info can be found here: https://docs.python.org/3/library/traceback.html

except Exception as e:
    print(e)
    traceback.print_exc(file=sys.stdout)

or save it as a variable first like the following:

except Exception as e:
    print(e)
    st = traceback.format_stack()
    print(st)

Upvotes: 0

alec_djinn
alec_djinn

Reputation: 10819

You need traceback. You can use it together with e. You should import it at the beginning of your code, you don't need to import it every time an exception occurs.

import traceback

try:
    ...
except Exception as e:
    tb = traceback.format_exc()
    print(e)
    print(tb)

Upvotes: 0

Related Questions