Python Glossary Русский

all Python 3sysfunction

sys.excepthook()

exceptions

The function the interpreter calls for an uncaught exception before the program exits; by default it prints the traceback to stderr.

Syntax

sys.excepthook = hook  # hook(exc_type, exc_value, exc_tb)

Replacing sys.excepthook lets you log any crash, but not survive it: after the hook runs the program still exits with status 1. The hook is not called for SystemExit (sys.exit) and never sees exceptions in threads — those go to threading.excepthook. Jupyter and IPython ignore the replacement because they install their own handler. The original hook lives in sys.__excepthook__; restore it from there.

Examples

import sys
def hook(exc_type, exc, tb):
    print('Сбой:', exc_type.__name__, exc)
sys.excepthook = hook
try:
    1 / 0
except ZeroDivisionError:
    sys.excepthook(*sys.exc_info())  # → Сбой: ZeroDivisionError division by zero
sys.excepthook = sys.__excepthook__
print(sys.excepthook is sys.__excepthook__)  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy