Try / Except / Finally in Python

From the Python cheat sheet ยท Error Handling ยท verified Jul 2026

Try / Except / Finally

Catch and handle exceptions gracefully.

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")
else:
    print("Success")        # Only runs if no exception
finally:
    print("Always runs")    # Cleanup
๐Ÿ’ก Use specific exception types โ€” bare "except:" catches everything including KeyboardInterrupt
โšก The else block runs only when no exception occurs โ€” great for success logic
๐Ÿ“Œ Use "raise" without arguments to re-raise the current exception
๐ŸŸข Custom exceptions should inherit from Exception, not BaseException
exceptionstryexcepterror-handling
Back to the full Python cheat sheet