try, except, else & finally in Python
A try block lets a program attempt something that might fail, catching any exception that occurs with a matching except block instead of crashing outright. An optional else block runs only if the try block succeeded with no exception, and an optional finally block runs no matter what happened — success, failure, or even an unhandled exception — making it the natural place for cleanup that must always happen.
try: wraps risky code
Code that might raise an exception goes inside.
except ExceptionType: catches a match
Runs its block instead of letting the program crash.
Multiple except blocks handle different types
Each exception type can be caught and handled separately.
else runs only on full success
Only if the try block completed with no exception at all.
finally always runs at the end
Whether or not an exception occurred — the standard place for cleanup like closing a file.
def safe_divide(a, b): try: result = a / b except ZeroDivisionError: print("Can't divide by zero!") else: print(f"Result: {result}") finally: print("Division attempt finished") safe_divide(10, 2)safe_divide(10, 0)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.