finally Block & Raising Exceptions in Python 🚀🐍

1️⃣ The finally Block in Python
The finally block always executes, no matter what happens in the try-except block. It is commonly used for cleanup tasks, like closing files or database connections.
✅ Basic finally Example
try:
print("Trying to execute...")
x = 10 / 2 # No error
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute!")
🔹 Output:
Trying to execute...
This will always execute!
✔ finally runs even when no exception occurs.
✅ finally Executes Even with Errors
try:
x = 10 / 0 # Causes ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero!")
finally:
print("This will always execute!")
🔹 Output:
Error: Division by zero!
This will always execute!
✔ finally still runs, even if an exception occurs.
✅ finally Ensures Cleanup (Closing a File)
The finally block is useful for resource management, like closing a file after reading it.
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
file.close() # Ensures the file is closed
print("File closed.")
✔ Guarantees that file.close() runs, preventing memory leaks.
2️⃣ Raising Exceptions (raise)
The raise keyword manually triggers an exception. This is useful when you want to enforce certain conditions in your code.
✅ Basic raise Example
x = -5
if x < 0:
raise ValueError("Negative numbers are not allowed!")
🔹 Output:
Traceback (most recent call last):
File "
ValueError: Negative numbers are not allowed!
✔ raise stops the program and shows a custom error.
✅ Raising Exceptions in Functions
def check_age(age):
if age < 18:
raise ValueError("You must be at least 18!")
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print(f"Error: {e}")
🔹 Output:
Error: You must be at least 18!
✔ The raise statement forces the error, and except catches it.
✅ Raising Custom Exceptions
You can define custom exceptions by creating a new class that inherits from Exception.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception!")
except CustomError as e:
print(f"Caught custom error: {e}")
🔹 Output:
Caught custom error: This is a custom exception!
✔ Useful for application-specific errors.
3️⃣ Summary
Concept Description
finally Block Runs always, even if an error occurs
finally for Cleanup Used to close files, release resources
raise Statement Manually triggers an exception
Custom Exception Create user-defined exceptions by subclassing Exception
Date: 2025-03-24 00:00:00.000000