Why only run finally statement? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why only run finally statement?

def h(x): try: return 1 except: return 2 finally: return 3 print(h(2)) #ouput=3 but why 1 not execute .

11th Apr 2018, 11:53 AM
Maninder $ingh
Maninder $ingh - avatar
1 Answer
+ 3
From the python documentation: "A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):"
11th Apr 2018, 12:15 PM
Hallox
Hallox - avatar