Python me Exception Handling kya hai?
Program chalate waqt kabhi kabhi kuch galat ho jaata hai — jaise zero se divide karna, galat type ki value dena, ya koi file na milna. Aise situations me Python ek Exception (error) raise karta hai aur program band ho jaata hai. Exception Handling se hum in errors ko gracefully handle kar sakte hain aur program ko crash hone se bacha sakte hain.
Is page me yeh sab sikhenge :-
- 1. Common Exceptions — Python ke built-in errors
- 2. try-except — basic error handling
- 3. Multiple except blocks
- 4. else aur finally
- 5. raise — khud error uthana
- 6. Custom Exceptions — apni class se error banana
- 7. Nested try-except
1. Common Exceptions — Python ke Built-in Errors
Python me bahut saare built-in exceptions hain. Inhe jaanna zaroori hai taaki sahi jagah handle kar sakein.
| Exception | Kab aata hai | Example |
|---|---|---|
| ZeroDivisionError | Zero se divide karo | 10 / 0 |
| TypeError | Galat type ka operation | "5" + 5 |
| ValueError | Sahi type, galat value | int("abc") |
| NameError | Variable exist nahi karta | print(xyz) |
| IndexError | List index out of range | lst[10] |
| KeyError | Dict me key nahi | d["missing"] |
| AttributeError | Object me attribute nahi | "hi".push() |
| FileNotFoundError | File nahi mili | open("xyz.txt") |
| RecursionError | Recursion limit exceed | infinite recursion |
| OverflowError | Number bahut bada | float overflow |
Example 1: Different errors naturally trigger karna
2. try-except — Basic Error Handling
try block me woh code likhte hain jo error de sakta hai. except block me woh code likhte hain jo error aane par chalega. Error aane par program crash nahi hoga — except block chal jaayega.
| Syntax |
|---|
try:
# code jo error de sakta hai
except ExceptionType as e:
# error aane par yeh chalega
print(e) # error message
|
Example 1: try-except — bina handle kiye vs handle karke
Example 2: Division function — safe divide
3. Multiple except Blocks
Ek try block me alag alag exceptions ke liye alag except likh sakte hain. Python upar se neeche check karta hai aur jo pehle match ho use chalata hai. Sabse broad exception Exception — isko hamesha sabse aakhir me likhein.
Example 1: Multiple exceptions — alag alag handle karna
Example 2: Ek except me multiple exceptions — tuple me likhna
4. else aur finally
else — sirf tab chalta hai jab try me koi error nahi aata.
finally — hamesha chalta hai — error aaye ya na aaye.
Yeh cleanup kaam ke liye use hota hai (jaise file band karna).
| Full Syntax |
|---|
try:
# code
except ErrorType:
# error par chalta hai
else:
# koi error nahi toh chalta hai
finally:
# HAMESHA chalta hai
|
Example 1: else aur finally ka flow samjhna
Example 2: finally — cleanup ka real example (file close)
5. raise — Khud Error Uthana
raise keyword se hum khud intentionally ek exception raise kar sakte hain — jab koi invalid input mile ya koi condition fail ho.
Example 1: raise — invalid input pe error uthana
Example 2: raise — error ko re-raise karna
6. Custom Exceptions — Apni Class Se Error Banana
Python me hum apni custom exception classes bana sakte hain — sirf Exception class se inherit karo. Yeh tab useful hota hai jab built-in errors se zyada specific error message chahiye ho.
Example 1: Simple custom exception
Example 2: Exception hierarchy — custom exceptions ka group
7. Nested try-except
Ek try block ke andar doosra try block — ise Nested try-except kehte hain. Jab ek operation me kaafi saari alag alag jagah errors aa sakti hain tab yeh useful hota hai.
Example 1: Nested try — student data process karna
Example 2: Poora example — try, except, else, finally, raise saath
Quick Summary — Exception Handling ek nazar me
| Concept | Kaam | Example |
|---|---|---|
| try | Risky code yahan likhna | try: x = 1/0 |
| except | Error pakadna | except ZeroDivisionError: |
| except as e | Error message lena | except ValueError as e: print(e) |
| Multiple except | Alag errors alag handle | except (TypeError, ValueError): |
| else | Koi error nahi toh | else: print("success") |
| finally | Hamesha chalega | finally: conn.close() |
| raise | Khud error uthana | raise ValueError("bad!") |
| Custom Exception | Apna error class | class MyError(Exception): |
| Exception | Sabse broad — base class | except Exception as e: |