finally
` block to execute code regardless of whether the `try
` block raises an error or not :try:
# Your code goes here
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This code will always be executed")
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.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")
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. finally
` block will always be executed, and it will close the file and print a message.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.try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output :
Something went wrong
The 'try except' is finished