Try-except-finally helps your program handle errors without crashing and always run important cleanup code.
0
0
Try–except–finally behavior in Python
Introduction
When you want to catch and handle errors like dividing by zero or missing files.
When you need to make sure some code runs no matter what, like closing a file or releasing resources.
When you want to keep your program running smoothly even if something unexpected happens.
When you want to give friendly messages to users instead of showing confusing errors.
Syntax
Python
try: # code that might cause an error except SomeError: # code to handle the error finally: # code that always runs
The try block is where you put code that might fail.
The except block runs only if an error happens in try.
The finally block runs no matter what, even if there is an error or not.
Examples
This example catches division by zero and always prints the final message.
Python
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("This always runs.")
Here, no error happens, so
except is skipped but finally still runs.Python
try: print("Hello") except Exception: print("Error happened") finally: print("Done")
Sample Program
This program tries to divide by zero, catches the error, and always runs the final print. It shows how the flow moves through try, except, and finally.
Python
def test_try_except_finally(): try: print("Start") result = 10 / 0 print("This won't print") except ZeroDivisionError: print("Caught division by zero") finally: print("Always runs") print("End") test_try_except_finally()
OutputSuccess
Important Notes
If no error happens, the except block is skipped but finally still runs.
You can have multiple except blocks for different error types.
The finally block is useful for cleanup like closing files or releasing resources.
Summary
try runs code that might fail.
except runs only if an error happens.
finally always runs, no matter what.