Python 3.11+sysfunction
sys.exception()
exceptions
Returns the exception currently being handled (inside an except block), or None. The modern replacement for sys.exc_info() since Python 3.11.
Syntax
sys.exception()
It helps where the name from except ... as e is out of reach: in a helper called from the handler or in a logger. Once the except block ends it returns None again — Python 3 clears the 'current' exception, so keep it in your own variable if you need it later. It equals sys.exc_info()[1] as a single object: the type is type(e) and the traceback is e.__traceback__. Python 3.10 and older lack it (AttributeError), so code for them still needs exc_info().
Examples
import sys
try:
int('abc')
except ValueError:
e = sys.exception()
print(type(e).__name__, e) # → ValueError invalid literal for int() with base 10: 'abc'
print(sys.exception()) # → None
import sys
def describe():
exc = sys.exception()
return 'нет ошибки' if exc is None else f'обрабатывается {exc!r}'
try:
{}['k']
except KeyError:
print(describe()) # → обрабатывается KeyError('k')
print(describe()) # → нет ошибки
See also
Open in the full glossarydocs.python.orgReport an inaccuracy