Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix exception handling with user interrupts (#224)

Akshay Agrawal9c13bcbe258c
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.py
index 2951e98f43..2b6f1e6684 100644
--- a/marimo/_runtime/cell_runner.py
+++ b/marimo/_runtime/cell_runner.py
@@ -82,7 +82,7 @@ class RunResult:
# Raw output of cell
output: Any
# Exception raised by cell, if any
- exception: Optional[Exception]
+ exception: Optional[BaseException]
def success(self) -> bool:
"""Whether the cell exected successfully"""
@@ -109,7 +109,7 @@ class Runner:
# whether the runner has been interrupted
self.interrupted = False
# mapping from cell_id to exception it raised
- self.exceptions: dict[CellId_t, Exception] = {}
+ self.exceptions: dict[CellId_t, BaseException] = {}
# each cell's position in the run queue
self._run_position = {
@@ -240,7 +240,9 @@ class Runner:
run_result = RunResult(output=e.output, exception=e)
# don't print a traceback, since quitting is the intended
# behavior (like sys.exit())
- except Exception as e: # noqa: E722
+ except BaseException as e: # noqa: E722
+ # except BaseException to catch everything, including
+ # KeyboardInterrupt: nothing should go uncaught
# cancel only the descendants of this cell
self.cancel(cell_id)
run_result = RunResult(output=None, exception=e)
diff --git a/marimo/_runtime/control_flow.py b/marimo/_runtime/control_flow.py
index 5de23d53fa..85198cfd32 100644
--- a/marimo/_runtime/control_flow.py
+++ b/marimo/_runtime/control_flow.py
@@ -4,14 +4,22 @@ from typing import Optional
from marimo._output.rich_help import mddoc
-class MarimoInterrupt(Exception):
- """User stops execution of entire program with interrupt."""
+class MarimoInterrupt(BaseException):
+ """Raised when user stops execution of entire program with interrupt.
+
+ Inherits from `BaseException` to prevent accidental capture with
+ `except Exception` (similar to `KeyboardInterrupt`)
+ """
pass
-class MarimoStopError(Exception):
- """Raised by `marimo.stop` to stop execution of a cell and descendants."""
+class MarimoStopError(BaseException):
+ """Raised by `marimo.stop` to stop execution of a cell and descendants.
+
+ Inherits from `BaseException` to prevent accidental capture with
+ `except Exception` (similar to `KeyboardInterrupt`)
+ """
def __init__(self, output: Optional[object]) -> None:
self.output = output
diff --git a/marimo/_runtime/test_runtime.py b/marimo/_runtime/test_runtime.py
index ac28260a02..479a4623e1 100644
--- a/marimo/_runtime/test_runtime.py
+++ b/marimo/_runtime/test_runtime.py
@@ -583,3 +583,45 @@ def test_set_config_before_registering_cell(
k.run([er_1])
assert k.graph.cells[er_1.cell_id].config.disabled
assert "x" not in k.globals
+
+
+def test_interrupt(k: Kernel, exec_req: ExecReqProvider) -> None:
+ er = exec_req.get(
+ """
+ from marimo._runtime.control_flow import MarimoInterrupt
+
+ tries = 0
+ while tries < 5:
+ try:
+ raise MarimoInterrupt
+ except Exception:
+ ...
+ tries += 1
+ """
+ )
+ k.run([er])
+
+ # make sure the interrupt wasn't caught by the try/except
+ assert k.globals["tries"] == 0
+
+
+def test_keyboard_interrupt_doesnt_crash_marimo(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ er = exec_req.get(
+ """
+ from marimo._runtime.control_flow import MarimoInterrupt
+
+ tries = 0
+ while tries < 5:
+ try:
+ raise KeyboardInterrupt
+ except Exception:
+ ...
+ tries += 1
+ """
+ )
+ k.run([er])
+
+ # make sure the kernel didn't crash ...
+ assert k.globals["tries"] == 0