Python prueba finalmente
Prueba finalmente
El finally
bloque, si se especifica, se ejecutará independientemente de si el bloque try genera un error o no.
Ejemplo
try:
print(x)
except:
print("Something went
wrong")
finally:
print("The 'try except' is finished")
Esto puede ser útil para cerrar objetos y limpiar recursos:
Ejemplo
Intente abrir y escribir en un archivo que no se puede escribir:
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")
El programa puede continuar, sin dejar abierto el objeto de archivo.