+ 4
Try, except and finally in python
We have a block named "finally" After try except blocks. Which ll surely run at the last. But my question is why do we need that block? Anything we write out of suite.. Runs definitely... Then why do we need such a block separately???
9 Antworten
+ 16
Yes, you can write what ever codes you've inside the finally block, to the outside finally and remove the finally. But doing that, you're guaranteeing that you'll always execute those commands after catching the exception, which may not be the case everytime.
In addition to this, as Anna suggested, it's used to write clean up codes. It's like a one time chance, to perform necessary clean-up like closing streams or freeing up resources. The code after the finally block might never be reached.
As it says in the Java tutorial:
It allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
+ 8
For example to make sure that an open file is closed no matter if an exception is raised or not (just put file.close() in the finally block and it will be executed in any case)
+ 8
In the 'except' block you would normally name specific exception types that you intend to handle, at least if you follow good design principles.
If any OTHER type of error occurs (whatever you did not expect), you will probably want your program to fail and exit - if that happens, you can decide how to fix that bug. But in the meantime, in the finally block you would free up system resources, close open files, disconnect from database and so on.
+ 3
#In fact, the lesson text presents the wrong example. The correct example is here: even if an error occurs and it is not caught by 'except', the code in 'finally' will still be executed:
try:
print("Hello")
print(1 / 0)
finally:
print("This code will run no matter what")
print("This code will not run")
+ 2
finally is used for any post processing, and object deallocation in python, C#,C ++ etc. 😅
+ 2
Qwe Wie It's execution is guaranteed ! 😉😀
+ 1
Тимофей Антонов The indent in the last statement is the key 🔑
0
Sanjay Kamath is arguments within 'finally' guaranteed to be executed even if there was an execution error before finally?