Finally
In the previous sections you have seen how to execute different blocks of code depending on the exception that is thrown as a result of an error. In Python there is an additional clause to add to the try-except construct called finally. This clause also defines a block of specific code that will be executed in all cases. That is, the finally block executes both if the try block is terminated without any exceptions, or any exception (both managed and unmanaged) has occurred.
try :
blocco try
except NomeEccezione1:
blocco except
except NomeEccezione2:
...
...
finally:
blocco finally
This allows you to be able to execute some instructions even if some unhandled exception occurs. Attention, that in this case the execution of the program would stop immediately after, reporting the error message.
For example, to see how well it works, let’s add the finally clause and cancel the management of the ZeroDivisionError.
a = 5
b = input("Inserisci un valore numerico: ")
try:
b = int(b)
res = a/b
print("5 / ",b," = ",res)
except ValueError:
print("Attenzione hai immesso un valore errato")
finally:
print("The show must go on!")
This time execute the code and enter the value 0 to generate the unhandled exception.
>>>
Inserisci un valore numerico: 0
The show nust go on!
Traceback (most recent call last):
File "C:/Python34/prova.py", line 5, in <module>
res = a/b
ZeroDivisionError: division by zero
⇐ Go to Python Lesson 4.2 – Handling Exceptions
Go to Python Lesson 4.4 – Raise an exception ⇒