如何在Python的try-except块中处理多次触发的相同类型异常?
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:
- The outer
trythrowsZeroDivisionErrorfrom10/0, triggering the firstexcept. - Inside that
except, the nestedtryruns20/0, which throws anotherZeroDivisionError. - The nested
exceptcatches 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

