What will be the output if you run this code?
A) Outer ZeroDivisionError exception caught
B) Error: You divided by zero!
C) Error: You divided by zero! Finally executed
D) Finally executed
E) None of the above
This tutorial is an excerpt from my book, The Python Quiz Book
The Answer
D) Finally executed
Explanation
This code causes the ZeroDivisionError
to be raised inside the nested exception handler because you are dividing by zero. Your exception handler catches this, but inside the exception handler, you raise ZeroDivisionError
so that the outer exception handler can run and perhaps handle it differently.
Before you get to the outer exception handler, though, the finally
statement must run. The finally
statement ALWAYS runs! Here you print out “Finally executed” and then call break
, and break
causes the newly raised ZeroDivisionError
to be discarded and the loop to end.
Try running the code through a debugger and see for yourself.
Special Thanks to Our Sponsor
Mindrift, a platform connecting experts with leading AI training projects, is looking for professionals in STEM. Want to train models to handle complex, multi-step challenges that mirror real-world research and workflows? Explore Mindrift’s freelance, project-based, flexible opportunities and apply today!