3 Python finally
1. What is finally in Python?
finally is a block used with try-except.
In simple words:
👉 Code inside finally always runs
👉 It runs whether an error happens or not
👉 It is used for clean-up work
2. Why Do We Use finally?
We use finally to:
-
Close files
-
Close database connections
-
Release resources
-
Print ending messages
Even if an error occurs, finally will run.
3. Simple try-except-finally Example
Example
Output:
4. finally Runs Even When Error Happens
Example
Output:
5. finally Without except
You can use finally without except.
Example
6. finally with File Handling
Very common use case.
Example
7. finally vs else
| else | finally |
|---|---|
| Runs only if no error | Runs always |
| Optional | Optional |
| Success block | Clean-up block |
8. finally with Return Statement
Even if function returns, finally still runs.
Example
9. Common Beginner Mistakes
❌ Thinking finally runs only on error
❌ Forgetting to use finally for cleanup
❌ Closing file outside finally
10. Simple Practice Examples
Example 1: Safe Division
Example 2: Always Print Message
Example 3: File Close Guarantee
11. Summary (Python finally)
✔ finally always runs
✔ Used with try-except
✔ Great for cleanup work
✔ Runs even if error or return
✔ Important for safe programs
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
raise Keyword
-
Custom Exceptions
-
Debugging Python
-
Mini Python Projects
Just tell me 😊
