0

Explain the control flow in try, except and finally blocks ?

try: print(1) print(10 / 0) except ZeroDivisionError: print(unknown_var) finally: print("This is executed last") in the above code when exception occured in the except block, the control went to finally block and then returns back to the except block to print the exception

11th Jul 2020, 7:05 AM
Saswata Das
Saswata Das - avatar
4 odpowiedzi
+ 6
Saswata Das Flow is simple 1 - try 2 - except 3 - finally If finally will be execute before the except then output will be different. Did you get different output? I didn't get.
11th Jul 2020, 7:10 AM
A͢J
A͢J - avatar
+ 6
try: if error occurs goto except else goto finally except: if error occurs it's propagated to the enclosing scope* and handled normally(after finally) and goto finally no matter what happened. finally: always runs. If error occurs it's handled as usual. *In your code the "unknown_var" error is not handled but consider: try: try: print(1) print(10/0) except ZeroDivisionError: print(unknown_var) finally: print("This is executed last") except: pass #do nothing
11th Jul 2020, 8:02 AM
Kevin ★
+ 4
Try is used to test the code. If any error occurs, the error mentioned in except block runs.. Note:- If any error is not mentioned, it takes all the errors. If the code in try block gives an error, the block in finally statements runs no matter what error occurs.... Then, it will give error of try statement, whatever error occurs is mentioned in except block.. That's why it first went to finally and gave the error of code mentioned in except block... Hope it is clear now 🙂
11th Jul 2020, 7:14 AM
Arctic Fox
Arctic Fox - avatar
+ 2
The code will first print 1, then it will check the next statement, 'print 10/0'. Since this statement will create an error (ZeroDivisionError). This error will get excepted by the statement 'except Zerodivisionerror'. It will then run the code in that block. As there is another error (undefined variable) under the except statement, it will not run that block. The 'finally' keyword will run the block of code no matter what, therefore, it will execute the statement 'print( 'this is executed last' )
11th Jul 2020, 7:20 AM
Partha Jagdale
Partha Jagdale - avatar