Python finally Keyword

Example

The finally block will always be executed regardless of whether an error is raised in the try block:

try:
  x > 3
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
finally:
  print("The try...except block is finished")

Running Instance

Definition and Usage

The finally keyword is used in the try ... except block. It defines a code block that will run when the try...except...else block ends.

The finally block will always be executed regardless of whether an error is raised in the try block.

This is very useful for closing objects and cleaning up resources.

Related Pages

try Keyword

except Keyword