"Error aana galti nahi hai… Error ko handle na karna galti hai!"
"Aaj hum seekhne wale hain Python ka sabse powerful tool: Error Handling – try, except, finally, raise, and custom exceptions."
"Production-level code bina iske kabhi complete nahi hota."
🔹 1. try – except Basics
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
📌 Why use try-except?
- App crash hone se bachata hai
- Controlled message milta hai user ko
- Bugs trace karne mein help karta hai
🔹 2. finally Block – Real Use
try:
file = open("data.txt", "r")
# read file
except FileNotFoundError:
print("File not found.")
finally:
print("Cleaning up resources...")
file.close()
📌 finally block always execute hota hai
📌 Real life:
- DB connections close karna
- File handle close karna
- Logging activity
🧠 Secret Tip: Even if you return
inside try/except – finally still runs.
🔹 3. raise Statement – Custom Errors
def set_age(age):
if age < 0:
raise ValueError("Age can't be negative.")
print("Age set to", age)
set_age(-5)
📌 Why raise?
- Apni conditions pe error throw kar sakte ho
- Helps in custom validation
🧠 Real Use:
- Form validation
- Data processing
- API request checks
🔹 4. Catching Multiple Exceptions
try:
# something risky
except (TypeError, ValueError):
print("Type or value error!")
📌 Use-case:
Agar similar type ke multiple error aa sakte ho – ek block se handle karo.
🔹 5. Custom Exception Class
class TooYoungError(Exception):
pass
def register(age):
if age < 18:
raise TooYoungError("You must be 18+ to register.")
print("Registered!")
try:
register(16)
except TooYoungError as e:
print("Custom Error:", e)
📌 Why use custom exceptions?
- Code readable banta hai
- Specific errors trace kar sakte ho
- Large codebase me error grouping easy hoti hai
🔹 6. Real-World Examples 🔥
✅ File Upload System
try:
upload_file("profile.png")
except FileSizeLimitError:
print("File too large.")
finally:
print("Logging upload activity...")
✅ API Integration
try:
data = fetch_data()
except TimeoutError:
print("Server is slow.")
finally:
log("API call attempted")
✅ Payment Processing
try:
process_payment()
except PaymentFailedError as e:
alert_admin(str(e))
finally:
update_transaction_status()
🔹 7. Pro Tips, Secrets & Mistakes 💣
🧠 Secret 1: Avoid catching base Exception
blindly
except Exception:
pass # Bad practice: hides bugs
🧠 Secret 2: Logging + Error Handling = 🧠
import logging
try:
do_task()
except SomeError as e:
logging.error("Error occurred: %s", e)
🧠 Secret 3: Use else
after try-except
try:
x = 5
except:
print("Error")
else:
print("No error occurred!")
🎯 Keep it up!
"Professional Python devs always write safe code – aur try-except-finally is the heart of that."
"Agle part me seekhenge ki python m hr chij ek opject hai kese object kam krte hai object model internal in python"