1.3.6 · HinglishPython Intermediate

Raising exceptions — raise, custom exception classes

1,802 words8 min readRead in English

1.3.6 · Coding › Python Intermediate


WHY do we raise at all?

Core trade-off (yahi 80/20 idea hai):

  • Return a value jab ek meaningful result ho (kabhi kabhi "not found" bhi).
  • Raise an exception jab continue karna ek bug ya invalid state hogi.

WHAT is raise?

raise ValueError("amount must be positive")   # instance created from class + message
raise ValueError                              # class — Python instantiates it with no args

HOW does it flow? (mechanism ko scratch se derive karo)

Jab raise run hota hai, Python yeh steps follow karta hai:

  1. Exception object banao (agar tumne class di hai, toh use call karo).
  2. Ek traceback attach karo jo record kare ki hum abhi kahan hain.
  3. Current line chodo; bahar koi matching except dhoondo.
  4. Is function ke andar enclosing try blocks check karo. Koi nahi? Yeh frame pop karo.
  5. Caller ke frame mein repeat karo... upar aur upar.
  6. Agar koi catch nahi karta, toh top tak pahunch jaata hai → program traceback print karta hai aur exit ho jaata hai.

Custom Exception Classes — WHY apna khud ka banao?

class InsufficientFundsError(Exception):
    """Raised when a withdrawal exceeds the balance."""
    pass

Ek richer custom exception derive karo (data carry karo!)

Kabhi kabhi handler ko sirf naam nahi, facts chahiye hote hain. __init__ add karo:


Figure — Raising exceptions — raise, custom exception classes

raise bina arguments ke — re-raising

raise ... from ... — exception chaining


Common Mistakes (Steel-man + fix)


Active Recall

Recall

raise ValueError aur raise ValueError("x") mein kya fark hai? Pehla class pass karta hai; Python use bina message ke instantiate karta hai. Doosra ek instance pass karta hai jisme message .args mein stored hota hai. Dono kaam karte hain.

Recall Custom exceptions ko kis class se inherit karna chahiye, aur

BaseException se kyun nahi? Exception se inherit karo. BaseException mein SystemExit/KeyboardInterrupt bhi aata hai, jo ordinary error handling mein nahi aana chahiye.

Recall

except ke andar bare raise kya karta hai? Current exception ko uske original traceback ke saath re-raise karta hai.

Recall

raise B from A kya accomplish karta hai? B.__cause__ = A set karta hai, exceptions ko chain karta hai taaki traceback original ko direct cause ke roop mein dikhaaye.


Recall Feynman: ek 12-saal ke bachchhe ko explain karo

Socho tum ek waiter ho order le rahe ho. Normally tum khaana laate ho (ek return value). Lekin agar kitchen mein aag lagi ho, toh tum khaana nahi la sakte — balki tum "AAG LAGI HAI!" chillate hue bhaagoge (yahi raise hai). Jo bhi sune (except) decide kar sakta hai kya karna hai: 911 call karo, ya aur zor se chillao taaki upar manager sun sake (re-raise). Ek custom exception alag specific shouts rakhne jaisi hai: "AAG!", "PIZZA KHATAM!", "BAND HO GAYE!" — taaki sunne waale ko pata ho exactly kaun si problem handle karni hai.


Connections

  • Try-Except-Finally — raised exceptions kaise catch hote hain
  • Exception Hierarchy & BaseException — jisse tum inherit kar rahe ho
  • Classes and __init__ — custom exception ka constructor banana
  • Logging in Python — log-and-re-raise pattern
  • assert statement — ek halka cousin jo AssertionError raise karta hai

Python mein exception throw karne wala statement kaun sa hai?
raise (followed by an exception instance or class)
Custom exceptions ko kis base class se inherit karna chahiye?
Exception
BaseException se inherit kyun nahi karte?
Isme SystemExit/KeyboardInterrupt bhi hai, jo normal handlers se catch nahi hone chahiye
except ke andar bare raise (no args) kya karta hai?
Current exception ko re-raise karta hai, uska traceback preserve karte hue
raise B from A kya karta hai?
Exceptions chain karta hai: B.__cause__ = A set karta hai taaki cause dikhe
Exception ka message kahan store hota hai?
Uske .args tuple mein, super().__init__(msg) se set hota hai
raise ValueError aur raise ValueError("x") mein fark?
Pehla class hai (auto-instantiated, no msg); doosra instance hai message ke saath
Error code return karne ki jagah raise kyun karo?
Caller ko problem handle karne par majboor karta hai; silent corrupt-state continuation rokta hai
Agar koi except raised exception ko kabhi catch na kare toh kya hota hai?
Yeh top tak propagate hota hai, traceback print hoti hai, aur program exit ho jaata hai
Data-carrying custom exception ko kaun sa method call karna chahiye, aur kyun?
super().__init__(message).args populate karne ke liye taaki str(e) sahi print ho

Concept Map

for real answers

for invalid state

interrupts

propagates

inherits from

ultimately from

walks up

matched by

if uncaught

can create

subclass of

enables

Return value

Meaningful result

raise statement

Bug or invalid state

Normal execution

Exception object

Exception class

BaseException

Call stack

except block

Traceback and exit

Custom exception class

Specific except handling