Learn Python
>>> exception_handling.try_except_finally

try, except, else & finally in Python

#concept

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.

#how it works
1

try: wraps risky code

Code that might raise an exception goes inside.

2

except ExceptionType: catches a match

Runs its block instead of letting the program crash.

3

Multiple except blocks handle different types

Each exception type can be caught and handled separately.

4

else runs only on full success

Only if the try block completed with no exception at all.

5

finally always runs at the end

Whether or not an exception occurred — the standard place for cleanup like closing a file.

#example
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)
Output
Result: 5.0
Division attempt finished
Can't divide by zero!
Division attempt finished
1safe_divide(10, 2) succeeds — the try block completes with no exception, so else runs and prints the result, and finally then runs afterward regardless.
2safe_divide(10, 0) raises a ZeroDivisionError — the except block catches it and prints a friendly message instead of crashing; else is skipped entirely, since the try block didn't complete successfully.
3finally runs both times, proving it executes unconditionally, whether the division succeeded or failed.
#use cases
Handling an expected failure gracefully, like a file that might not exist or a network request that might time out
Ensuring cleanup code (closing a file, releasing a lock) always runs with finally, regardless of what happened
Separating the 'happy path' logic (in else) from the actual risky operation (in try), for clearer code
Catching several different, specific exception types separately, handling each one appropriately

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.