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