Python Exception Handling
In this page:
try:
# code that may raise an error
except ExceptionType:
# handle the error
Exception क्या है?
Exception एक error है जिसे Python आपका program चलते समय पहचानता है (इसके विपरीत, syntax error शुरू होने से पहले ही पकड़ लिया जाता है) -- अगर इसे कोई नहीं handle करता, तो exception ऊपर की ओर propagate होकर traceback के साथ program को crash कर देता है, इसी वजह से उस code के लिए handling मायने रखती है जिसे अनायास रुकना नहीं चाहिए।
उदाहरण: What is an Exception?
try:
print(1 / 0) # raises ZeroDivisionError at runtime
except ZeroDivisionError:
print("Caught an exception instead of crashing")
Built-in Exceptions
Python कई specific built-in exception types के साथ आता है -- ZeroDivisionError, TypeError, ValueError, और भी बहुत कुछ -- और bare except की बजाय आप जिस specific type की उम्मीद करते हैं उसे catch करना आपकी error handling को सटीक बनाता है, बजाय इसके कि वह गलती से unrelated bugs छुपा ले।
उदाहरण: Built-in Exceptions
try:
int("abc")
except ValueError: # catches only this specific error type
print("Caught a specific ValueError")
Exceptions Raise करना
raise keyword आपके अपने code को जानबूझकर एक exception trigger करने देता है, यही तरीका है जिससे आप किसी function के अंदर गहराई से 'यह input अमान्य है' का संकेत देते हैं -- raise ValueError('age must be positive') वहीं execution रोक देता है और caller के except block को तय करने देता है कि कैसे प्रतिक्रिया दी जाए।
उदाहरण: Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError("age must be positive") # deliberately triggers an exception
return age
try:
set_age(-5)
except ValueError as e:
print(e)
Custom Exceptions बनाना
built-in Exception class को subclass करना आपको अपने application के domain के लिए specific अपने खुद के exception types (जैसे InsufficientFundsError) बनाने देता है, जो generic exceptions जाँचने और यह अंदाज़ा लगाने से कहीं ज़्यादा readable error handling code बनाता है कि वाकई क्या गलत हुआ।
उदाहरण: Creating Custom Exceptions
class InsufficientFundsError(Exception): # custom exception type for this domain
pass
try:
raise InsufficientFundsError("Not enough balance")
except InsufficientFundsError as e:
print(e)
Exception Hierarchy
हर built-in exception अंततः base Exception class से inherit करता है, इसलिए except Exception: block लगभग हर वह error catch कर लेता है जो आपका code raise करता है -- पर इतनी व्यापक रूप से catch करना production code के लिए आमतौर पर बहुत ज़्यादा crude है, क्योंकि यह उन bugs को भी छुपा देता है जिनके बारे में आप जानना चाहेंगे।
उदाहरण: Exception Hierarchy
try:
int("abc")
except Exception as e: # catches virtually any error, since all inherit from Exception
print("Caught by the base Exception class:", type(e).__name__)
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: