w3resource

Python finally block: Ensuring code execution and error handling with examples

How can you ensure that Python code within the finally block is executed, even if an exception occurs?

The finally block always runs after the "try" and "except" blocks, regardless of any exceptions. This ensures that the code in the "finally" block will be executed regardless of whether an exception is raised or not. Here's the basic structure:

try:
    # Code that may raise an exception
    # ...
except SomeException:
    # Exception handling code
    # ...
finally:
    # Code that will be executed no matter what
    # ...

Example-1:

Code:

try:
    x = 100 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Division by zero!")
finally:
    print("Final block: This will always be printed.")

Output:

Division by zero!
Final block: This will always be printed.

Example-2:

Code:

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

Output:

File not found.
Closing file
Traceback (most recent call last):
  File "C:\Users\ME\untitled18.py", line 9, in <module>
    file.close()
NameError: name 'file' is not defined

Note: Run on Spyder (Python 3.6).



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/how-can-you-ensure-that-python-code-within-the-finally-block-is-executed-even-if-an-exception-occurs.php