Python Glossary Русский

Python 3.8+sysfunction

sys.unraisablehook()

exceptions

The function that receives exceptions with nowhere to propagate: from __del__, finalizers and the garbage collector. By default it prints them to stderr.

Syntax

sys.unraisablehook = hook  # hook(unraisable)

An error in __del__ does not stop the program and cannot be caught by a try around del — it goes here, leaving only 'Exception ignored in …' on screen. That is why such bugs survive for years; test suites expose them by swapping this hook. The hook gets one object with exc_type, exc_value, exc_traceback, err_msg and object fields. Keeping exc_value after the hook returns is risky: it can resurrect an object that is being destroyed.

Examples

import sys
seen = []
sys.unraisablehook = lambda u: seen.append((u.exc_type.__name__, str(u.exc_value)))
class Bad:
    def __del__(self):
        raise RuntimeError('del failed')
b = Bad()
try:
    del b
except RuntimeError:
    print('поймано')
sys.unraisablehook = sys.__unraisablehook__
print(seen)  # → [('RuntimeError', 'del failed')]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy