How to Use try except else finally in Python
Demonstrates the correct order of try/except/else/finally blocks in Python with a safe division function.
Python code
17 linesdef safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Both arguments must be numbers!")
else:
print(f"Division successful: {numerator} / {denominator} = {result}")
finally:
print("Operation complete.\n")
if __name__ == "__main__":
safe_divide(10, 2) # Normal case
safe_divide(10, 0) # Zero divisor case
safe_divide(10, "a") # TypeError case
Output
Division successful: 10 / 2 = 5.0
Operation complete.
Error: Cannot divide by zero!
Operation complete.
Error: Both arguments must be numbers!
Operation complete.
How it works
The try block contains code that might raise an exception. The except clauses catch specific exceptions (ZeroDivisionError and TypeError) and handle them gracefully. The else block runs only if no exception occurred, allowing you to use the successful result. The finally block always executes, regardless of exceptions, making it ideal for cleanup actions like closing files or releasing resources. This structure keeps error handling, success logic, and cleanup code clearly separated.
Common mistakes
- Placing the `else` block before `except` — it must come after all except clauses.
- Returning inside `finally` can override a return value from `try` or `except`.
- Forgetting that `finally` runs even if `sys.exit()` is called in the `try` block.
Variations
- Use `except Exception as e:` to catch any exception and access its message.
- Combine multiple exception types in one tuple: `except (ZeroDivisionError, TypeError):`.
Real-world use cases
- Dividing two numbers from user input, handling zero and invalid types with distinct messages.
- Processing a file: read data in `try`, validate in `except`, log success in `else`, and close the file in `finally`.
- Making an API call and retrying on network errors while ensuring the connection is closed in `finally`.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.