+ 3
Can anyone explain the "finally" concept in programming?
I doesn't understand the concept of "finally" In the Python . Even the comments are also I can't understand. Explain elaborately.
5 Respuestas
+ 12
Cracker is right.
I would add that finally will execute even if "return" is met:
def test(x,y):
try: res = x/y
except: return ("mmmh, we had a problem")
finally: print("I will always be printed")
return res
print(test(3,2))
print(test(3,0))
+ 5
Side note: Because finally blocks are executed in any case, you can use them to clean up your code even if there's an exception:
try:
f = open('file.dat', 'wt')
f.write(5/0)
except ZeroDivisionError:
print('Can\'t divide by 0')
finally:
f.close()
print('file was closed')
Without the "finally" statement, a ZeroDivisionError would be raised and the program would be terminated without explicitly closing the file that was previously opened. The finally statement makes sure that the file is closed in any case (which is important to allow other processes to access the file).
+ 4
The finally block will be executed no matter if the try block raises an error or not.
consider this example,
try:
x > 3
except:
print("Error!")
finally:
print("The try-except block is completed")
# The finally clause will always execute after the try-except clause!
+ 2
It's an extension of the try-catch block
It executes compulsorily
It's usually used for garbage collection 😎
+ 2
Finally block is used to run commands that must be executed whether your programme run successfully or not for example backup commands and close database connection
it enhance the security and performance