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

如何在Python的try-except块中处理多次触发的相同类型异常?

How to Handle Sequential Same-Type Exceptions in Python Try-Except Blocks

Got it, let's break down why your code isn't behaving the way you expect and fix it step by step.

The Problem with Your Original Code

First, let's look at what's happening in your code:

try:
    d = 10/0
except ZeroDivisionError as e :
    d=20/0
except ZeroDivisionError as f:
    print("yes")

When 10/0 throws a ZeroDivisionError, the program jumps to the first except ZeroDivisionError block. But when you run d=20/0 inside that block, this new exception isn't covered by the outer try's subsequent except clauses.

Here's the key rule: Each try block's except clauses only handle exceptions thrown directly within that try block. Once you enter an except block, you're outside the scope of the original try—any exceptions thrown here need their own error handling.

In your case, the second ZeroDivisionError from 20/0 has no except to catch it, so the program crashes instead of printing "yes".

The Fix: Nested Try-Except Blocks

To handle the exception from the second function call, you need to wrap that call in its own try-except inside the first except block. Here's the corrected code:

try:
    d = 10/0
except ZeroDivisionError as e:
    # Nested try-except to handle the second operation's exception
    try:
        d = 20/0
    except ZeroDivisionError as f:
        print("yes")

When you run this:

  1. The outer try throws ZeroDivisionError from 10/0, triggering the first except.
  2. Inside that except, the nested try runs 20/0, which throws another ZeroDivisionError.
  3. The nested except catches this second error and prints "yes" as you expected.

A Quick Note on Duplicate Except Clauses

Also, keep in mind that having multiple except clauses for the same exception type under a single try is redundant. Python checks except clauses in order—once it finds a matching type, it stops checking the rest. Your original code's second except ZeroDivisionError would never run, even if the first except didn't throw an error.

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:17:56