try...except...else in Python
In Python, the else block in exception handling is often misunderstood. It is not required, but it is extremely useful for writing clean and readable code.
Basic Syntax
try:
# Code that might raise an exception
except SomeException:
# Code that runs if an exception occurs
else:
# Code that runs ONLY if no exception occurs Explanation
- try block: Contains code that might cause an error.
- except block: Runs only if an exception occurs in the try block.
- else block: Runs only if no exception was raised in the try block.
Think of it as: “If everything went fine, then execute this part.”
Example: Basic try-except-else
Python
try:
# Code that may cause an error
num = int(input("Enter a number: ")) # May raise ValueError if input is not numeric
except ValueError:
# Runs if an error occurs
print("That's not a valid number!")
else:
# Runs only if no exception occurs
print(f"You entered {num}, which is valid.") Output Examples
If user inputs 10:
Output
You entered 10, which is valid.
If user inputs abc:
Output
That's not a valid number!
Example: File Handling with else
Python
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found!")
else:
# Only runs if file was opened successfully
print("File opened successfully!")
content = file.read()
print(content)
file.close() Why use else here? The file operations (read, close) only make sense if the file opened correctly. So, it is safer to place them in the else block instead of the try block.
Example: With finally
Python
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful! Result =", result)
finally:
print("Execution finished (this always runs).") Output:
Output
Division successful! Result = 5.0 Execution finished (this always runs).
When to Use else
- Use else when code should run only if the try block succeeds.
- It separates risky code from safe follow-up logic.
- Improves readability and clean structure.
Common Mistake
Do not put code that might raise an error inside the else block. The else block should contain code that is expected to run safely.
Summary
| Block | Runs When | Example Use |
|---|---|---|
| try | Code that may cause an error | Risky code execution |
| except | When an error occurs | Error handling logic |
| else | When no error occurs | Follow-up successful logic |
| finally | Always runs | Cleanup resources (files, DB, etc.) |