PCEP-30-02 · Question #231
What is the expected behavior of the following program? ``python try: print(5/0) break except: print("Sorry, something went wrong...") except (ValueError, ZeroDivisionError): print("Too bad...") ``
The correct answer is B. The program will cause a SyntaxError exception. Option B is correct because Python detects two syntax errors before the program ever runs: a bare except: clause cannot be followed by another except clause (Python requires the bare except to be last, and raises SyntaxError: default 'except:' must be last), and break appears…
Question
try:
print(5/0)
break
except:
print("Sorry, something went wrong...")
except (ValueError, ZeroDivisionError):
print("Too bad...")
Options
- AThe program will cause a ValueError exception and output a default error message.
- BThe program will cause a SyntaxError exception.
- CThe program will cause a ZeroDivisionError exception and output a default error message.
- DThe program will cause a ValueError exception and output the following message: Too bad...
- EThe program will raise an exception handled by the first except block.
How the community answered
(26 responses)- A4% (1)
- B77% (20)
- D4% (1)
- E15% (4)
Explanation
Option B is correct because Python detects two syntax errors before the program ever runs: a bare except: clause cannot be followed by another except clause (Python requires the bare except to be last, and raises SyntaxError: default 'except:' must be last), and break appears outside of any loop, which is also a SyntaxError. Since Python compiles the code before executing it, these structural violations are caught immediately - no line of the try block ever runs.
Options A, C, D, and E all assume the program actually executes, which it cannot. While 5/0 would raise a ZeroDivisionError at runtime (making C tempting), and the first bare except would catch it (making E tempting), neither scenario is reached. Options A and D are doubly wrong because no ValueError is raised by integer division; 5/0 always produces ZeroDivisionError, not ValueError.
Memory tip: Think of Python as a proofreader before a speaker - it checks the whole script for structural mistakes before saying a word. If the script is malformed (break outside a loop, bare except not last), it throws SyntaxError immediately, regardless of what the code would have done at runtime.
Community Discussion
No community discussion yet for this question.