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

Python me bahut saare built-in exceptions hain. Inhe jaanna zaroori hai taaki sahi jagah handle kar sakein.

ExceptionKab aata haiExample
ZeroDivisionErrorZero se divide karo10 / 0
TypeErrorGalat type ka operation"5" + 5
ValueErrorSahi type, galat valueint("abc")
NameErrorVariable exist nahi kartaprint(xyz)
IndexErrorList index out of rangelst[10]
KeyErrorDict me key nahid["missing"]
AttributeErrorObject me attribute nahi"hi".push()
FileNotFoundErrorFile nahi miliopen("xyz.txt")
RecursionErrorRecursion limit exceedinfinite recursion
OverflowErrorNumber bahut badafloat overflow

Example 1: Different errors naturally trigger karna

Python
In [1]:
1
Output


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

Python
In [1]:
1
Output

Example 2: Division function — safe divide

Python
In [1]:
1
Output


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

Python
In [1]:
1
Output

Example 2: Ek except me multiple exceptions — tuple me likhna

Python
In [1]:
1
Output


4. else aur finally

else — sirf tab chalta hai jab try me koi error nahi aata.
finallyhamesha 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

Python
In [1]:
1
Output

Example 2: finally — cleanup ka real example (file close)

Python
In [1]:
1
Output


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

Python
In [1]:
1
Output

Example 2: raise — error ko re-raise karna

Python
In [1]:
1
Output


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

Python
In [1]:
1
Output

Example 2: Exception hierarchy — custom exceptions ka group

Python
In [1]:
1
Output


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

Python
In [1]:
1
Output

Example 2: Poora example — try, except, else, finally, raise saath

Python
In [1]:
1
Output



Quick Summary — Exception Handling ek nazar me

ConceptKaamExample
tryRisky code yahan likhnatry: x = 1/0
exceptError pakadnaexcept ZeroDivisionError:
except as eError message lenaexcept ValueError as e: print(e)
Multiple exceptAlag errors alag handleexcept (TypeError, ValueError):
elseKoi error nahi tohelse: print("success")
finallyHamesha chalegafinally: conn.close()
raiseKhud error uthanaraise ValueError("bad!")
Custom ExceptionApna error classclass MyError(Exception):
ExceptionSabse broad — base classexcept Exception as e: