How do I use try/except/else/finally for error handling in Python?

· Category: Python Programming

Short answer

Wrap risky code in a try block, catch specific exceptions with except, run success-only code in else, and guarantee cleanup in finally. Catch specific exceptions rather than a bare except:.

Steps

  1. Place the operation that might fail inside try.
  2. Catch expected exceptions with except SpecificError:.
  3. Use else for code that runs only when no exception occurs.
  4. Use finally for cleanup that must always run.
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    except TypeError:
        print("Invalid input type")
        return None
    else:
        print("Division succeeded")
        return result
    finally:
        print("Cleanup complete")

print(divide(10, 2))
print(divide(10, 0))

Tips

  • Catch the most specific exception possible; catching Exception broadly can mask unexpected bugs.
  • Use raise without an argument inside an except block to re-raise the same exception after logging.
  • Context managers (with) are often cleaner than try/finally for resource management.
  • Exception hierarchy matters: catch subclasses before their parent classes.

Common issues

  • A bare except: catches SystemExit, KeyboardInterrupt, and GeneratorExit, which is usually undesirable.
  • Overly broad exception handling makes debugging difficult.
  • Swallowing exceptions without logging or re-raising them hides problems.