Home >>Python Keywords >Python finally Keyword

Python finally Keyword

Python finally Keyword

The finally keyword python is used to always executed after try and except blocks irrespective of whether the exception is handled or not. If the try block raises an error or not, the finally block will be executed. The finally block always executes after try block terminates due to some exception or after normal termination of try block.

Here is an example of Python finally Keyword:

try:
  x > 5
except:
  print("Something went wrong")
else:
  print("All is well")
finally:
  print("The try...except block is finished")

Output:
Something went wrong
The try...except block is finished
Example 2:

try:
  y > 10
except:
  print("All is not well")
else:
  print("All is well")
finally:
  print("The try...except block is finished")

Output:
All is not well
The try...except block is finished

No Sidebar ads