The following context manager causes any exceptions raised inside it to print a stack trace and exit immediately. The calling scope is not given a chance to catch the exception.
1 2 3 4 5 6 7 8 9 10
from contextlib import contextmanager @contextmanager def failnow(): try: yield except Exception: import sys sys.excepthook(*sys.exc_info()) sys.exit(1)
Some larger frameworks are designed to allow individual jobs or requests to fail. They log the exception and continue. During debugging it can be convenient to force a piece of code to fail immediately. Another situation where this might be useful is while developing a complex exception handling code where you want errors in the handler not to be handled by itself.
Cleanup handlers in 'finally' statements and context managers are executed normally (unless using os._exit instead of sys.exit).