Python try-except-else
Using else in Python Exception Handling
In Python, the else block can be added after try and except blocks. It runs only if no exceptions occur in the try block.
Syntax
try:
# Code that may raise an exception
except SomeException:
# Handle the exception
else:
# This runs only if no exception occurredExample 1: Simple try-except-else
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)Output:
Division successful: 5.0Explanation:
- No error occurs, so
exceptis skipped. - The
elseblock runs because everything intrysucceeded.
Example 2: else Block is Skipped When Exception Occurs
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Division successful:", result)Output:
Error: Division by zeroExplanation:
- Since
10 / 0raises aZeroDivisionError, theexceptblock runs. - The
elseblock is skipped.
When to Use else in Exception Handling
Use else when:
- You want to execute code only if no exceptions occur.
- It improves readability by separating error-handling code from successful-path logic.
Best practice: Keep the try block focused only on code that might raise exceptions. Move the “happy path” logic to the else block.