Python Tutorial Python Advanced Python References Python Libraries

Python finally Keyword



The Python finally keyword is used in exception handling and finally block of statement is executed regardless of try-except block results.

Syntax

try:
  statements
except:
  statements
finally:
  statements

Example:

In the example below, finally block of statement is executed regardless of try-except block results, which facilitates the program to close the file before proceeding further.

MyFile = None
try:
  MyFile = open("math_example.txt")
  x = MyFile.readline()
  y = MyFile.readline()
  x = x/y
  print(x)
except:
  print("An error occurred.")
finally:
  if MyFile == None:
    print("MyFile does not exist.")
  else:
    print("MyFile has been closed.")
    MyFile.close()

The output of the above code will be:

An error occurred.
MyFile does not exist.

❮ Python Keywords