Python try-except
In this page:
try:
# risky code
except ExceptionType as error:
# handle error
except (TypeA, TypeB):
# handle either
try-except Block
try block के अंदर का code पहले चलता है, और अगर उसमें कोई statement कोई exception raise करता है, तो execution आगे बढ़ने की बजाय तुरंत matching except block पर चला जाता है -- अगर कोई exception नहीं होता, तो except block को बस पूरी तरह skip कर दिया जाता है।
उदाहरण: The try-except Block
try:
print(10 / 2) # no exception raised here
except ZeroDivisionError:
print("This does not run")
कई Exceptions Handle करना
कई except clauses लिखना आपको अलग-अलग error types को अलग-अलग तरह से handle करने देता है (missing file और bad data को अलग-अलग fixes चाहिए), या जब उन्हें एक ही तरह handle किया जाना हो तो आप संबंधित exception types को एक ही except (ValueError, TypeError): block में group कर सकते हैं।
उदाहरण: Handling Multiple Exceptions
try:
int("abc")
except (ValueError, TypeError): # handles either exception type the same way
print("Caught ValueError or TypeError")
Exception को Variable के रूप में Catch करना
'except ValueError as e:' exception object को एक variable में save करता है ताकि आप str(e) से उसका असली message देख सकें, जो 'कहीं ValueError हुआ' जानने से कहीं ज़्यादा logging या debugging के लिए उपयोगी है।
उदाहरण: Catching Exception as Variable
try:
int("abc")
except ValueError as e: # saves the exception object for inspection
print(str(e))
Nested try-except Blocks
एक try/except को दूसरे try/except के अंदर रखना आपको fallback recovery action try करने देता है और उस recovery में होने वाली विफलताओं को भी catch करने देता है -- यह 'primary server try करो, और अगर उस तक पहुँचना fail हो तो backup server try करो, और उसकी विफलता भी handle करो' जैसी चीज़ों के लिए उपयोगी है।
उदाहरण: Nested try-except Blocks
try:
try:
raise ConnectionError("primary server down")
except ConnectionError:
raise ConnectionError("backup server also down") # failure of the fallback itself
except ConnectionError as e:
print(e)
Bare except से बचना
बिना किसी exception type वाला bare 'except:' literally सब कुछ catch कर लेता है, जिसमें KeyboardInterrupt जैसी चीज़ें भी शामिल हैं जिन्हें कोई user program रोकने के लिए जानबूझकर trigger कर सकता है -- इसकी बजाय 'except Exception:' catch करना सामान्य errors तो catch करता है पर उन system-level signals को गुज़रने देता है।
उदाहरण: Avoiding Bare except
try:
int("abc")
except Exception as e: # catches ordinary errors but lets KeyboardInterrupt through
print("Caught ordinary errors, not KeyboardInterrupt:", e)
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: