# Stretch Driver双重try-catch致Ctrl-C时stop()未可靠执行

> 原文链接：https://robotics.hellobike.com/pitfalls/2026-01-28-stretch-ros2-159
> 频道：pitfalls | 更新日期：2026-01-28 | 标签：auto, github-issue, stretch_ros2
> 核心摘要：Stretch Driver循环中双重try-catch导致中断时节点先于停止指令销毁，建议将stop()移至内层finally块并补充单元测试。

# Stretch Driver双重try-catch致Ctrl-C时stop()未可靠执行

::: v-pre
> 本文由 AI 根据公开内容整理，可能有误，请以原文为准：[Double try-catch](https://github.com/hello-robot/stretch_ros2/issues/159)（GitHub hello-robot/stretch_ros2 #159）

**状态**：有绕过办法

## 问题

在Stretch Driver主循环的双重`try-catch`结构中，当`executer.spin()`运行时触发`Ctrl-C`，Python会先执行内层`finally`再进入`except`块。这导致ROS2节点在发送机器人停止指令前被销毁，使得`stop()`命令无法可靠执行，机器人可能维持最后接收的运动指令而非安全停止。

## 环境

hello-robot-stretch-robots, Stretch Driver, ROS2, Python

## 解决办法

1. 修改异常处理逻辑，将`robot.stop()`与`gamepad_teleop.stop()`调用从外层`except`块移动至内层`finally`块中，确保在`destroy_node()`之前优先执行停止指令。
2. 新增单元测试验证中断安全性，通过Mock `robot`和`gamepad_teleop`对象，断言在`spinning`期间发生`KeyboardInterrupt`时，两个组件的`stop()`方法均被正确调用且先于节点销毁。
3. 提交PR修复该问题，确保中断信号能触发确定性的安全停机序列，避免依赖外层异常捕获的不确定性行为。

讨论原作者：@hello-binit 等，版权归原作者所有。
:::

## 原始参考来源 (Sources)

- [GitHub hello-robot/stretch_ros2 #159：Double try-catch](https://github.com/hello-robot/stretch_ros2/issues/159)