You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python单个try-except块中处理多异常并执行后续代码?

单个try-except块实现需求的方案

可以用单个try-except块达成目标,直接修改代码如下:

try:
    print(10/0)
    print(10/2)
except Exception as e:
    print(e)
    print(10/2)

原理说明

当print(10/0)触发除数为零的异常时,程序会立刻跳转到except块执行:

  1. 先打印捕获到的异常信息division by zero
  2. 接着手动执行原本在try块中未被执行到的print(10/2),输出5.0

如果try块的第一个语句没有抛出异常(比如把10/0改成10/5),那么两个print都会正常执行,except块不会被触发,逻辑完全符合预期。

另外还有一种嵌套内部小try-except的写法,属于单个顶级try-except块的范畴,适合需要对后续语句也做异常兜底的场景:

try:
    try:
        print(10/0)
    except Exception as e:
        print(e)
    print(10/2)
except Exception as e:
    print(e)

这种写法里,外层try-except作为全局兜底,内部小try-except处理第一个语句的异常,后续的print(10/2)如果出错也会被外层捕获。

内容的提问来源于stack exchange,提问作者hoa.le

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:52:19