Python prova finalmente
Prova finalmente
Il finally
blocco, se specificato, verrà eseguito indipendentemente dal fatto che il blocco try generi un errore o meno.
Esempio
try:
print(x)
except:
print("Something went
wrong")
finally:
print("The 'try except' is finished")
Questo può essere utile per chiudere oggetti e ripulire le risorse:
Esempio
Prova ad aprire e scrivere su un file che non è scrivibile:
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")
Il programma può continuare, senza lasciare aperto l'oggetto file.