Lesson 17 � Intermediate
TRY/EXCEPT:
ERROR HANDLING.
Errors inevitable hain � user galat input dega, file nahi milegi, API fail hogi. Error handling se program crash nahi hota gracefully handle hota hai. Ye lesson sikhaega ki Python mein errors ko kaise catch, handle aur custom errors kaise banayein.
WHY: Error handling kyun zaroori hai?
Socho aap ek program likh rahe ho jisme user se number lena hai. User ne "abc" type kar diya � program crash! Ya file read kar rahe ho aur file exist nahi karti � crash! Error handling se aap in situations ko gracefully handle kar sakte ho. Program rokna nahi, smart tarike se aage badhana hai.
Code try karo, error aaye toh handle karo � program crash nahi hoga.
Chahe error ho ya na ho, finally hamesha chalega � cleanup ke liye best.
Khud se error throw karo � custom validation ke liye use hota hai.
Alag alag errors ke liye alag handling � ValueError, ZeroDivisionError, etc.
WHEN: kab error handling use hota hai
Error handling tab use hota hai jab aapko pata hai ki kuch galat ho sakta hai � user input lene mein, files padhane mein, network calls karne mein, database operations mein. Har production-ready application mein error handling mandatory hai.
HOW: try/except se error handle karo
Basic try/except
try:
num = int(input("Number daalo: "))
print(100 / num)
except ValueError:
print("Galat number!")
except ZeroDivisionError:
print("Zero se divide mat karo!")
except Exception as e:
print(f"Error: {e}")
else:
print("Sab theek hai!")
finally:
print("Cleanup done.")try block mein wo code daalo jo error de sakta hai. except mein specific error handle karo. else tab chalega jab koi error na ho. finally hamesha chalega � chahe error ho ya na ho.
Multiple except blocks
try:
data = {"name": "Aman"}
print(data["age"])
except KeyError as e:
print(f"Key nahi mili: {e}")
except TypeError as e:
print(f"Type error: {e}")
except Exception as e:
print(f"Kuch aur gaya wrong: {e}")Har error ka apna except block rakho � debugging mein help milti hai. Exception sabse last mein rakho kyunki ye sab errors catch karta hai.
Custom errors raise karna
class AgeError(Exception):
pass
def check_age(age):
if age < 0:
raise AgeError("Age negative nahi ho sakta!")
if age > 150:
raise AgeError("Ye realistic age nahi hai!")
return True
try:
check_age(-5)
except AgeError as e:
print(f"Validation error: {e}")raise se khud error throw kar sakte ho. Custom error class banake apne validation rules define karo � code clean aur readable rahega.
Try/Except flow
# Flow: try ? (error?) ✓ except OR else ✓ finally
try:
print("Try: Koshish kar rahe hain")
result = 10 / 0
except ZeroDivisionError:
print("Except: Error mila, handle kar rahe hain")
else:
print("Else: Koi error nahi tha!")
finally:
print("Finally: Hamesha chalega!")
# Output:
# Try: Koshish kar rahe hain
# Except: Error mila, handle kar rahe hain
# Finally: Hamesha chalega!Agar try mein error aata hai toh except chalega, else skip hoga. Agar koi error nahi toh else chalega. finally hamesha last mein chalega � cleanup ke liye best.
Common Python errors
ValueError� Sahi type nahi hai, jaiseint("abc")ZeroDivisionError� Zero se divide karne ki koshishFileNotFoundError� File exist nahi kartiKeyError� Dictionary mein key nahi haiIndexError� List mein index exist nahi kartaTypeError� Sahi data type nahi haiAttributeError� Object mein wo attribute nahi haiImportError� Module import nahi ho raha
Quick check
try/except block likho jo string "abc" ko integer mein convert kare aur ValueError handle kare.
Pehle try: mein int("abc") likho, phir except ValueError: mein error message print karo.
Common mistakes
- Bare
except:lagana bina error type ke � hamesha specific error catch karo. finallyblock bhool jaana � cleanup code wahan likho jo hamesha chale.- Sirf
except Exceptionlagana � specific errors pehle catch karo, generic baad mein. tryblock mein bahut zyada code daalna � sirf risky code rakho try mein.- Error ko silently ignore karna �
except: passse debugging mushkil ho jaati hai.
print(e) ya logging use karo.Ab aap apne programs mein errors ko gracefully handle kar sakte ho � program crash nahi hoga, user ko proper message milega.