+ 2
But what is the difference between using finally and just another line of code after the the whole try/except part?
2 Respostas
+ 4
imagine a scenario in which you
1.) open some sort of connection (network related or towards other kinds of hardware), then
2.) perform communication and calculation operations and after workload completion
3.) safely close the connection, as is required so the next connection can be established afterwards, by the same process or others.
unless you make use of the try-catch-finally arrangement such as
1.) open connection
try:
2.) perform workload
except:
log exception etc.
finally:
3.) safely close connection
you're running in danger of ending up with 'broken connections' that will block further communication, since the code for closing up the connection is not reached in case of an exception.
..hope that helps!
+ 1
The main difference is that 'finally' block will run in any case even if you do not handle all types of exceptions. E.g. if you handle the zero division error in a try block but get a type error than no further line of code will run unless you use the finally keyword.
Plus the 'finally' statment will run even if one of the 'except' statements throws an exception.(!)