ros2
runtime_error
ai_generated
true
rclpy.executors.ExternalShutdownException: Context must be initialized before use
ID: ros2/executor-spin-error
88%Fix Rate
88%Confidence
3Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2 | active | — | — | — |
Root Cause
Node shutdown was triggered externally (Ctrl+C) while the executor was spinning. Context is no longer valid.
genericWorkarounds
-
92% success Wrap spin in try/except for graceful shutdown
try: rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass finally: node.destroy_node(); rclpy.try_shutdown()
-
90% success Use rclpy.try_shutdown() instead of rclpy.shutdown() for safe cleanup
-
85% success Register an on_shutdown callback for resource cleanup
context.on_shutdown(cleanup_function)
Dead Ends
Common approaches that don't work:
-
Catch the exception and keep spinning
90% fail
Context is already destroyed; continued spinning causes undefined behavior and potential segfault
-
Call rclpy.init() again after shutdown
78% fail
Multiple init/shutdown cycles are fragile and leak resources in many RMW implementations