Python finally और else
In this page:
try:
# risky code
except ExceptionType:
# handle error
else:
# runs if no error
finally:
# always runs
else Block
try/except से जुड़ा else block तभी चलता है जब try block बिना कोई exception raise किए पूरा हो जाए -- इससे 'सफलता पर' चलने वाला code उस risky code से साफ़ अलग रहता है जिसे guard किया जा रहा है, बजाय इसके कि उसे try block के अंत में ही जोड़ दिया जाए।
उदाहरण: The else Block
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
else: # runs only because the try block succeeded
print("Success:", result)
else Block का असली Example
एक typical उपयोग है try block में file खोलना और else block में उससे पढ़ना -- अगर खोलना fail हो जाए, तो आप गलती से पढ़ने की कोशिश नहीं करना चाहते, और उन्हें try/else में अलग करना इस गारंटी को implicit की बजाय explicit बनाता है।
उदाहरण: The else Block Real Example
try:
f = open("data.txt", "w")
f.write("saved")
except OSError:
print("Could not open file")
else: # only reached if opening and writing above succeeded
f.close()
print("File written and closed")
finally Block
finally block हमेशा चलता है चाहे कुछ भी हो -- चाहे try सफल रहा हो, कोई exception catch हुआ हो, या यहाँ तक कि exception बिल्कुल भी catch न हुआ हो -- इसी वजह से यह database connection या file handle बंद करने जैसे resources release करने की standard जगह है।
उदाहरण: The finally Block
try:
print(10 / 2)
finally: # runs whether or not an exception occurred
print("This always runs")
Complete try-except-else-finally Flow
try, except, else, और finally को एक ही structure में जोड़ना आपको चार अलग-अलग phases देता है: risky code, error handling, सिर्फ़-सफलता पर चलने वाला follow-up code, और guaranteed cleanup -- हर एक की अपनी साफ़, अलग ज़िम्मेदारी, उलझे हुए conditional logic की बजाय।
उदाहरण: Complete try-except-else-finally Flow
try:
value = int("42")
except ValueError:
print("Conversion failed")
else:
print("Converted:", value) # runs only on success
finally:
print("Done") # runs regardless
Return Values और finally
भले ही try या else block के अंदर एक return statement execute हो, Python फिर भी function के caller को वाकई return होने से पहले finally block चलाता है -- यह गारंटी देता है कि आपका cleanup code तब भी चले जब function return के ज़रिए जल्दी exit हो रहा हो।
उदाहरण: Return Values and finally
def safe_divide(a, b):
try:
return a / b
finally:
print("Cleanup runs even though we returned") # finally still runs before returning
print(safe_divide(10, 2))
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: