Computer Science · Ch 1 — Exception Handling in Python
try...except...else clause
try...except...else clause
The try...except block can be extended with an optional else clause. This clause is placed after all the except blocks and before the end of the try statement. The key idea is that the code inside the else block runs only if no exception was raised in the try block. If any exception occurs and is caught by an except block, the else block is skipped entirely.
This structure is useful for separating the "risky" code that might fail (inside try) from the code that should only execute on success (inside else). It makes the logic clearer and avoids accidentally catching exceptions that the else code itself might raise.
Program 1-5: Use of else clause
print("Handling exception using try...except...else")
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = (numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
else:
print("The result of division operation is ", quotient)
Here is how the program behaves in different scenarios:
- If the user enters a non-zero integer (e.g.,
5): Thetryblock runs without error. Theexceptblocks are skipped, and theelseblock executes, printing the result of the division. - If the user enters
0: Thetryblock raises aZeroDivisionError. The firstexceptblock catches it, prints the error message, and theelseblock is not executed. - If the user enters a non-integer (e.g.,
"abc"): Theint()function raises aValueError. The secondexceptblock catches it, prints the message, and theelseblock is skipped.
The textbook also mentions a case where a ZeroDivisionError is raised but no specific handler for it exists. In that scenario, a generic except clause (without any exception type) would catch it. However, in Program 1-5, a specific except ZeroDivisionError is provided, so that handler runs instead. …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.
This is the output of Program 1-5, which introduces the try...except...else structure, run with a valid denominator. After RESTART:, the program prints Handling exception using try...except...else, prompts for the denominator, and the user enters 5. The division inside try succeeds, so Division performed successfully is printed from inside the try block itself.
Because no exception occurred, the except block is skipped, and instead the else clause runs — this is the whole point of adding else to a try...except: code placed there executes only when the try block completed with no exception at all. Here that else block prints The result of division operation is 10.0, showing the computed quotient (50 divided by 5). …