+ 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???

19th Mar 2019, 6:54 AM
Manpreet Kaur
Manpreet Kaur - avatar
9 Respuestas
+ 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.
19th Mar 2019, 11:37 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 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)
19th Mar 2019, 7:53 AM
Anna
Anna - avatar
+ 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.
19th Mar 2019, 12:52 PM
Tibor Santa
Tibor Santa - avatar
+ 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")
21st Apr 2021, 11:10 AM
Tima
+ 2
finally is used for any post processing, and object deallocation in python, C#,C ++ etc. 😅
8th Aug 2021, 3:11 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
Qwe Wie It's execution is guaranteed ! 😉😀
10th Aug 2021, 11:15 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
Тимофей Антонов The indent in the last statement is the key 🔑
10th Aug 2021, 11:24 PM
Sanjay Kamath
Sanjay Kamath - avatar
0
Sanjay Kamath is arguments within 'finally' guaranteed to be executed even if there was an execution error before finally?
10th Aug 2021, 3:41 PM
Qwe Wie