B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Finally Block | LiveCodeProgramming

Python finally Block

In Python, the finally block is used to define cleanup actions that must be executed under all circumstances, even if an exception is raised or not.

Python में finally block का उपयोग cleanup code के लिए किया जाता है, जो हर हाल में चलता है चाहे exception आए या न आए।

Example 1: try-except-finally

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("This block always executes.")

Even though the error occurred, the finally block was executed.

यहाँ error आने के बाद भी finally block चला।

Example 2: No Error, Still finally Runs

try:
    print("Hello")
except:
    print("Error occurred.")
finally:
    print("Finally block executed.")

Even if no exception occurs, finally block will still run.

अगर कोई error नहीं भी आता, तब भी finally block चलेगा।

Example 3: Using finally to close file

try:
    f = open("data.txt", "r")
    data = f.read()
    print(data)
except FileNotFoundError:
    print("File not found.")
finally:
    print("Closing file.")
    try:
        f.close()
    except:
        pass

Use finally to safely close files, even if an error occurs while opening or reading.

file close करने के लिए finally का उपयोग किया गया है।