Google News
logo
Python Program to Use the finally block to execute code regardless if the try block raises an error or not
In the following example of a Python program that demonstrates how to use the `finally` block to execute code regardless of whether the `try` block raises an error or not :
Program :
try:
    # Your code goes here
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    print("This code will always be executed")
In this example, the `try` block contains the code that you want to execute. If an error occurs, the program will jump to the `except` block and execute the code inside it. Regardless of whether an error occurs or not, the program will always execute the code inside the `finally` block.

For example, here's a program that attempts to read a file and prints its contents :
Program :
try:
    file = open("example.txt", "r")
    print(file.read())
except FileNotFoundError as e:
    print(f"File not found: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    file.close()
    print("File closed")
In this program, the `try` block attempts to open and read a file named "example.txt". If the file exists, its contents will be printed. If the file does not exist, a `FileNotFoundError` exception will be raised and the code in the `except` block will be executed.

Regardless of whether an error occurs or not, the code in the `finally` block will always be executed, and it will close the file and print a message.

Note that the `finally` block is often used for tasks that must be performed regardless of whether an error occurs or not, such as closing files or database connections, releasing resources, or cleaning up temporary files.

Another Example :
try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Output :

Something went wrong
The 'try except' is finished