+ 1
Why is the first try code prints after finally but the second try not? Why print(3/0) break the code? Thanks
try: print("Hello") print(1 / 0) except ZeroDivisionError: print("Divided by zero") finally: print("This code will run no matter what") print('wow') *******Result******** Hello Divided by zero This code will run no matter what wow ************ try: print(1) print(2/0) print(2) except ZeroDivisionError: #print("Divided by zero") print(3/0) finally: print(4) print('wow') print(5) print('fghgghhh') *******Result******** 1 4 ************
3 Respuestas
+ 2
finally don't work like a exception. It runs everytime after the try and except blocks.
So you need an another try and except block inside the second except block.
The code crashes so the rest don't will be executed.
+ 1
On the first code it executes the first line without an error so it prints Hello. The next line throws the div by zero error. Then except kicks in and prints the Divided by zero. Then the finally code prints the other two lines.
In the second block of code the print(1) runs without error so you get a 1. Then the 2/0 throws the divide by zero error. The except has a commented out print statement (#) so that text is not printed. Then the div by zero error happens in the except code 3/0 and as noted by Stefanoo this crashes the program. The 4 is printed from the finally block and the run ends
+ 1
Thank you Stefanoo I got it now.If any errors occur, the codes below will not be executed.
Except finally :)