+ 1

Finally before Except

The below code does not even print Hello; it ends with a syntax error. While compiling, doesn't the compiler consider finally at the end of the program, no matter where it is mentioned? try: print("Hello") print(1 / 0) finally: print("This code will run no matter what") except ZeroDivisionError: print("Divided by zero")

28th Dec 2016, 4:50 PM
Dawood Ghasletwala
Dawood Ghasletwala - avatar
4 Respostas
+ 2
you are slightly wrong... finally or except block wont work without try block... in your code.. except block is creating the syntax error not finally block
28th Dec 2016, 5:15 PM
harihara
harihara - avatar
+ 1
i think exception should be before finally
28th Dec 2016, 5:00 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
+ 1
python considers finally as the end of the exception block not the end of the program... In your program finally block is stating the end of the try block so later except block is present without any try block which is a syntax error as except block can't be present without try block... hope that answers
28th Dec 2016, 5:02 PM
harihara
harihara - avatar
+ 1
Thanks Harihara. So, if I now understand it correctly, finally would never work without a try/except.
28th Dec 2016, 5:06 PM
Dawood Ghasletwala
Dawood Ghasletwala - avatar