Python Exception Hierarchy
In this page:
try:
# code
except SpecificError:
# handle specific first
except Exception:
# then more general
BaseException Class
BaseException Python के exception tree के बिल्कुल ऊपर बैठा है -- SystemExit और KeyboardInterrupt जैसे system-level exceptions सहित हर exception अंततः इससे inherit करता है, यही ठीक वजह है कि 'except Exception:' catch करना जानबूझकर इन दोनों को catch नहीं करता (वे hierarchy में Exception को छोड़कर आगे निकल जाते हैं)।
उदाहरण: The BaseException Class
print(issubclass(SystemExit, BaseException))
print(issubclass(SystemExit, Exception))
Exception Class
Exception लगभग हर 'सामान्य' error का parent है जिसे आपका code raise या catch करेगा, और यह वह class है जिसे documentation आपके अपने custom exceptions को inherit करने की सलाह देती है -- except Exception: catch करना व्यापक है पर फिर भी उन system-exit signals को छोड़ देता है।
उदाहरण: The Exception Class
try:
int("abc")
except Exception as e: # parent of nearly every normal error
print("Caught by Exception:", type(e).__name__)
ArithmeticError Family
ArithmeticError math से जुड़ी विफलताओं को एक umbrella के नीचे group करता है -- ZeroDivisionError (zero से divide करना) और OverflowError (एक result जो represent करने के लिए बहुत बड़ा है) दोनों इससे inherit करते हैं, इसलिए ArithmeticError catch करना उन्हें अलग-अलग list किए बिना दोनों को संभाल लेता है।
उदाहरण: The ArithmeticError Family
try:
1 / 0
except ArithmeticError: # ZeroDivisionError inherits from ArithmeticError
print("Caught a ZeroDivisionError via ArithmeticError")
LookupError Family
LookupError दो सबसे आम 'वह नहीं मिला' errors को group करता है -- IndexError (list index out of range) और KeyError (dictionary key missing) -- जिससे आप एक ही except clause लिखकर दोनों तरह की lookup विफलता संभाल सकते हैं।
उदाहरण: The LookupError Family
try:
[1, 2][5]
except LookupError: # IndexError inherits from LookupError
print("Caught an IndexError via LookupError")
Catching का क्रम
चूँकि except clauses ऊपर से नीचे जाँचे जाते हैं और पहला match जीतता है, आपको ज़्यादा specific exception types को उनके ज़्यादा general parent classes से पहले list करना होगा -- सबसे पहले रखा गया except Exception: block उसके बाद लिखे हर specific handler को चुपचाप निगल जाएगा।
उदाहरण: Order of Catching
try:
1 / 0
except ZeroDivisionError: # more specific handler, checked first
print("Specific handler runs first")
except Exception:
print("This would swallow everything if placed first")
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: