Exception Handling (try/except)
Jab kuch galat ho jaata hai — zero se divide karna, aisa text number mein convert karna jo actually number hai hi nahi — Python ek exception raise karta hai. Agar catch na kiya jaaye to yeh aapka program crash kar deta hai. try/except aapko use catch karne deta hai aur decide karne deta hai ki iske bajaye kya hoga.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")You cannot divide by zero!
Python try ke andar ka code run karne ki koshish karta hai. Jaise hi ek ZeroDivisionError hota hai, yeh seedha matching except block mein jump kar jaata hai crash hone ke bajaye — uske baad program normally chalta rehta hai.
Actual error ko catch karna, aur finally
except SomeError as e aapko actual error object access karne deta hai — logging ke liye ya generic ke bajaye ek real message dikhane ke liye useful hai. finally hamesha run hota hai chahe kuch bhi hua ho — exception raise hua ho ya nahi — isliye cleanup code ke liye yahi sahi jagah hai.
try:
number = int("not a number")
except ValueError as e:
print(f"Error: {e}")
finally:
print("This always runs")Error: invalid literal for int() with base 10: 'not a number' This always runs
Bare except ke bajaye specific exception types (ZeroDivisionError, ValueError) catch karo — isse ek genuinely unexpected bug us error ke saath chup chaap swallow nahi hoga jiski aap expect kar rahe the.
Aage: classes — data aur uspar kaam karne wale functions ko saath mein bundle karna.
Practice Exercise
String "abc" ko int mein convert karne ki koshish karo, ValueError catch karo, aur crash hone ke bajaye "Not a number" print karo.