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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

17 lines
Python 3.9+
def 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

stdout
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

  1. Use `except Exception as e:` to catch any exception and access its message.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.