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 occurred
Example 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.0
Explanation:
- No error occurs, so
except
is skipped. - The
else
block runs because everything intry
succeeded.
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 zero
Explanation:
- Since
10 / 0
raises aZeroDivisionError
, theexcept
block runs. - The
else
block 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.