Exception Handling (try/except)
Jab kuch ghalat ho jaata hai — zero se divide karna, aisa text number mein convert karna jo asal mein number hai hi nahi — Python ek exception raise karta hai. Agar pakra na jaaye to yeh aapka program crash kar deta hai. try/except aapko use pakarne aur decide karne deta hai ke 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 chalane ki koshish karta hai. Jaise hi ek ZeroDivisionError hota hai, yeh seedha matching except block mein chala jaata hai crash hone ke bajaye — uske baad program normal tor par chalta rehta hai.
Asal error ko pakarna, aur finally
except SomeError as e aapko asal error object tak rasaai deta hai — logging ke liye ya generic ke bajaye ek real message dikhane ke liye kaam aata hai. finally hamesha chalta hai chahe kuch bhi hua ho — exception raise hui 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 khaas exception types (ZeroDivisionError, ValueError) pakro — isse ek waqai ghair mutawaqqa bug us error ke sath khamoshi se nigla nahi jaayega jiski aap tawaqqo kar rahe the.
Aage: classes — data aur uspar kaam karne wale functions ko sath mein jorna.
Practice Exercise
String "abc" ko int mein convert karne ki koshish karo, ValueError pakro, aur crash hone ke bajaye "Not a number" print karo.