all Python 3tracebackfunction
traceback.format_exc()
formatting tracebacks
The traceback of the exception being handled as one string — what a crash prints, but in a variable: for a log, a file or an email.
Syntax
text = traceback.format_exc(limit=None, chain=True)
It only works inside an except block (or a function called from one): outside handling it returns the string 'NoneType: None\n' rather than failing, and an empty report is easy to miss. If the exception was raised inside another except, the text includes the first one too, after "During handling of the above exception…"; chain=False keeps only the last. For logging, logger.exception('…') is shorter: it appends the same traceback itself.
Examples
import traceback
try:
1 / 0
except ZeroDivisionError:
text = traceback.format_exc()
print(text.splitlines()[0]) # → Traceback (most recent call last):
print(text.splitlines()[-1]) # → ZeroDivisionError: division by zero
import traceback
print(repr(traceback.format_exc())) # → 'NoneType: None\n'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy