+ 1
Purpose of finally when you can run code without it!
Both the below codes runs the same way. Where is finally used: try: print("Hello") print(1 / 0) except ZeroDivisionError: print("Divided by zero") print("This code will run no matter what") OR try: print("Hello") print(1 / 0) except ZeroDivisionError: print("Divided by zero") finally: print("This code will run no matter what")
3 Respuestas
+ 4
Try this code with and without finally and you will see the difference. The code is from the python course too:
try:
print(1)
print(10 / 0)
except ZeroDivisionError:
print(unknown_var)
finally:
print("This is executed last")
+ 3
You could use a finally block to ensure that code is always executed.
The finally block is there for code that will get executed whether or not there is an exception raised anywhere, including inside the else or the except, and whether or not that exception is handled. The canonical use case for this is making absolutely sure that a file handle is closed, no matter what.*
finally is executed regardless of whether the statements in the try block fail or succeed. else is executed only if the statements in the try block don't raise an exception.
+ 2
A finally block is the place to "clean-up" after the mess happened having failed to pass the try block, in this case it is not necessary, but if you have resources used that needs proper steps done prior to leaving (e.g. open file handles needed to be released), you can do it inside finally block.