How strong is the "finally" keyword | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

How strong is the "finally" keyword

Consider this code: def func() : try : return 1 # we expect the function to #end here # since it is a return #statement finally : return 2 # but we also know that #finally gets # executed no matter what print(func()) # it outputs 2, so can anyone explain what exactly happened here, please?

19th Mar 2018, 12:10 PM
Khushal Sahni
Khushal Sahni - avatar
2 Antworten
+ 3
Since there is a finally, the return within the try skips to the finally. Once finished, the try return would happen, but you all ready returned skipping that code. Your best bet is to set a return variable to 2 before the try. Set it to 1 in the try and let the try exit. In the finally, return the variable.
19th Mar 2018, 1:01 PM
John Wells
John Wells - avatar
+ 3
oh Thanks a lot Sir ! @John
19th Mar 2018, 1:15 PM
Khushal Sahni
Khushal Sahni - avatar