Home βΊ Problems βΊ try-except-else flow
try-except-else flow
π§ Predict the output Topic: exceptions Difficulty: medium Free
What this problem practises
Exceptions are control flow. except clauses are matched top to bottom, finally runs even after a return, and catching too broadly hides the real bug behind a generic message.
This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.
Difficulty: medium β expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.
The challenge
The code runs in PyDebugβs in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.
The snippet
The interactive editor pre-fills exactly this code β read it, then submit your prediction:
def check(n):
try:
result = 10 / n
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"Result is {result}")
check(2)
check(0)Understand the rule
try/except/else has a precise execution order: the try body runs; if it raises a matching exception, the except body runs and else is skipped; if nothing raises, else runs after the try completes. else exists to hold code that should run only on success but should NOT be shielded by the except. Predicting these snippets is purely about which branch the exception decision selects.
How to trace it
- Execute the try body line by line until it either completes or raises.
- On a raise: jump to the first matching except; remaining try lines never run, and else is skipped.
- On success: skip every except and run the else block.
- Append finally output last in every scenario, if present.
Common wrong fixes
- Expecting else to run after a handled exception β it is the no-exception branch, not an 'afterwards' branch.
- Forgetting that lines in try after the raising line are abandoned.
- Confusing else with finally: finally always runs, else only on success.
Rule to remember
try's else is the success branch: it runs only when no exception fired. Exception β except only; no exception β else; finally β always.
π¨ Learning path: Exceptions
Problem 5 of 10 in this path. Work them in order β each one builds on the rule before it.
β Division by zero in a list comprehensionNext in path: Next problem β
πΌ Learning path: Interview Practice
Problem 15 of 16 in this path. Work them in order β each one builds on the rule before it.
β Default parameter valuesNext in path: String multiplication and indexing β
More exceptions problems
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every exceptions problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.