1.3.7 · HinglishPython Intermediate

Exception hierarchy

2,282 words10 min readRead in English

1.3.7 · Coding › Python Intermediate

Structure: General se Specific Tak

Figure — Exception hierarchy

Python mein har exception BaseException se inherit karti hai. Yeh raha derived-from-scratch logic:

Python ko BaseException top pe kyun chahiye?

  • Saare exceptions ka EK common ancestor hone ke liye
  • Taaki except Exception: "normal" errors ko catch kar sake bina system-exit events ko pakde

Main Branches:

BaseException
├── SystemExit          # sys.exit() calls
├── KeyboardInterrupt   # Ctrl+C
├── GeneratorExit       # Generator cleanup
└── Exception           # ← Normal errors start here
    ├── StopIteration
    ├── ArithmeticError
    │   ├── ZeroDivisionError
    │   ├── OverflowError
    │   └── FloatingPointError
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    ├── OSError
    │   ├── FileNotFoundError
    │   ├── PermissionError
    │   └── ConnectionError
    └── ... many more

Derivation: Catching Kaise Kaam Karta Hai

FIRST PRINCIPLES SE: Jab Python raise dekhta hai, woh exception hierarchy mein upar jaata hai aur matching except clause dhundta hai.

Step-by-step:

  1. Exception raise hui: KeyError('missing_key')
  2. Python check karta hai: Kya except KeyError hai? ✓ Match!
  3. Nahi mila toh parent check karo: Kya except LookupError hai? ✓ Match!
  4. Nahi mila toh grandparent check karo: Kya except Exception hai? ✓ Match!
  5. BaseException tak ya koi handler nahi mila tab tak continue karo (crash)

Yeh ordering kyun matter karti hai:

# ❌ WRONG - Dead code below!
try:
    data[key]
except Exception as e:      # Catches EVERYTHING first
    print("General error")
except KeyError as e:        # NEVER REACHED - KeyError is a child of Exception
    print("Key missing")

Kyun? Python handlers ko top se bottom check karta hai. KeyError IS-A Exception hai, isliye pehla handler hamesha jeet jaata hai.

# ✅ CORRECT - Specific to general
try:
    data[key]
except KeyError as e:        # Checked first - catches KeyError
    print(f"Missing key: {e}")
except LookupError as e:     # Catches IndexError (sibling of KeyError)
    print(f"Lookup failed: {e}")
except Exception as e:       # Catches everything else
    print(f"Unexpected: {e}")

Worked Examples

Common Mistakes & Steel-manning

Recall Feynman Explanation (12-saal ke bacche ko samjhao)

Socho tumhara teacher tumse saare animals organize karne ko bol raha hai. Tum keh sakte ho:

  • LivingThings (tree ka top)
    • Animals
      • Mammals
        • Dogs, Cats, Whales
      • Birds
        • Parrots, Eagles

Python errors ke saath bhi yahi karta hai! "Animals" ki jagah humara "Exceptions" hai. "Mammals" ki jagah "ArithmeticError" (math problems) ya "LookupError" (kuch find nahi ho raha) hai.

Jab tum except Mammals likhte ho, tum automatically saare dogs aur cats pakad lete ho. Jab except Dogs likhte ho, tum SIRF dogs pakadते ho.

Rule: Agar tum dog pakadna chahte ho, tum "catch dogs" ya "catch mammals" ya "catch animals" keh sakte ho—teeno kaam karte hain kyunki dogs teeno families mein belong karta hai. Lekin agar tumhe sirf dogs se matlab hai, specific raho! "Catch dogs" kaho taaki accidentally cats na pakad lo.

Python mein: except KeyError (specific) vs except LookupError (KeyError + IndexError pakadta hai) vs except Exception (almost sab kuch pakadta hai).

Connections

  • 1.3.06-TryExcept-Finally — Basic exception syntax (precise catching ke liye hierarchy use karo)
  • 1.3.08-Custom-Exceptions — Hierarchy mein apne khud ke exception classes banao
  • 1.3.09-Context-Managerswith statements use karo (jo internally exception handling pe rely karte hain)
  • 2.1.04-Inheritance — Exception hierarchy class inheritance use karti hai (IS-A relationships)
  • 3.2.05-Logging — Exceptions ko proper specificity ke saath log karo (bare except se swallow mat karo)

#flashcards/coding

Python ki exception hierarchy ki root kya hai?
BaseException (SystemExit, KeyboardInterrupt, aur Exception ka parent)
Normal error handling ke liye except BaseException ki jagah except Exception kyun use karna chahiye?
BaseException SystemExit aur KeyboardInterrupt ko catch karta hai, jo program termination aur Ctrl+C ko kaam karne se rok deta. Exception sirf normal errors pakadta hai.
KeyError aur IndexError dono ka parent exception kya hai?
LookupError (dono LookupError ke children hain)
Specific exception handlers general ones se pehle kyun aane chahiye?
Python handlers ko sequentially top-to-bottom check karta hai. Agar general handler (jaise except Exception) pehle aaye, toh woh child exceptions ko specific handlers se pehle pakad leta hai, unhe unreachable dead code bana deta hai.
ArithmeticError ke teen children batao
ZeroDivisionError, OverflowError, FloatingPointError
Agar tum KeyError raise karo aur tumhare handler mein sirf except LookupError ho toh kya hoga?
LookupError handler ise pakad lega, kyunki KeyError IS-A LookupError hai (inheritance)
Specific handlers ki jagah except OSError kab use karoge?
Specific handlers (FileNotFoundError, PermissionError) ke baad safety net ke roop mein, unexpected OS-level errors jaise disk full ya network failures ko pakadne ke liye
except Exception: pass production code mein kyun dangerous hai?
Yeh silently saari errors swallow kar leta hai, bugs sameta, debugging impossible ho jaati hai. Tumhe pata hi nahi chalta kab cheezein fail ho rahi hain.
Kya 10**1000 / 10**999 OverflowError raise karta hai?
Nahi—yeh 10.0 equal karta hai. Integer division correctly promote hota hai. OverflowError sirf FLOAT operands ke saath hota hai jinka result max float (~1.8e308) se zyada ho, jaise 1e308 / 1e-10.

Concept Map

parent of

parent of

parent of

child of

child of

child of

specializes to

specializes to

specializes to

specializes to

caught by handler for

prevents

BaseException

SystemExit

KeyboardInterrupt

Exception

ArithmeticError

LookupError

OSError

ZeroDivisionError

IndexError

KeyError

FileNotFoundError

Specific before General

Dead Code