Python Try Finally


Try Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")
Try it Yourself »

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:

try:
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")
Try it Yourself »

The program can continue, without leaving the file object open.



Copyright 1999-2023 by Refsnes Data. All Rights Reserved.