Batu Lab NotesPractical developer guides

Recognize an unhandled BaseException boundary

By Batu · English technical notes

To recognize an unhandled BaseException boundary, use except Exception for ordinary application failures and let KeyboardInterrupt propagate. KeyboardInterrupt derives from BaseException, not Exception; therefore, it crosses an except Exception boundary unchanged.

This fixture raises KeyboardInterrupt("stop") directly rather than requiring an actual keyboard signal. The first helper is the failure case. Its except BaseException catches the interrupt and converts it into an ordinary returned status. Doing so can prevent a caller from seeing the interruption and making its own shutdown decision. The second helper changes only the handler class to Exception. Its except suite cannot match the synthetic interrupt, so an outer test boundary catches KeyboardInterrupt solely to make the experiment’s output deterministic.

The assertions demonstrate boundary behavior, not a complete shutdown design: no signal is delivered, no resource is cleaned up, and a real application may need explicit shutdown coordination. Catch BaseException only when code intentionally owns exceptional control-flow signals and has a clear policy for them. The Python exception hierarchy identifies BaseException as the common base and describes KeyboardInterrupt as an exception normally allowed to terminate the program; the tutorial likewise advises handling expected exception types specifically. Built-in exceptions documentation and Python error handling tutorial.

AI-assistance disclosure: This article was drafted with AI assistance and uses a synthetic raised interrupt.

def broad_boundary():
    try:
        raise KeyboardInterrupt("stop")
    except BaseException as error:
        return f"caught {type(error).__name__}"


def ordinary_error_boundary():
    try:
        raise KeyboardInterrupt("stop")
    except Exception:
        return "caught ordinary error"


result = broad_boundary()
assert result == "caught KeyboardInterrupt"
print(f"broad boundary: {result}")

try:
    ordinary_error_boundary()
except KeyboardInterrupt as error:
    propagated = error

assert type(propagated) is KeyboardInterrupt
assert str(propagated) == "stop"
print(f"narrow boundary: propagated {type(propagated).__name__}")
broad boundary: caught KeyboardInterrupt
narrow boundary: propagated KeyboardInterrupt