PCEP-30-02 · Question #244
QUESTION 272 What is the expected output of the following code? try: raise BaseException: except BaseException: print('1') except Exception: print('2') except: print('3')
The correct answer is C. 1. Option C is correct because Python evaluates except clauses top to bottom, stopping at the first match. Since raise BaseException raises a BaseException instance, the very first clause - except BaseException: - matches immediately and prints '1'; the remaining clauses are never…
Question
Options
- AThe code is erroneous.
- B3
- C1
- D2
How the community answered
(39 responses)- A5% (2)
- B5% (2)
- C79% (31)
- D10% (4)
Explanation
Option C is correct because Python evaluates except clauses top to bottom, stopping at the first match. Since raise BaseException raises a BaseException instance, the very first clause - except BaseException: - matches immediately and prints '1'; the remaining clauses are never evaluated.
- A is wrong because the colon after
raise BaseExceptionin the question is a display artifact; the code itself is valid Python that runs without error. - B is wrong because the bare
except:clause (which would print'3') is never reached - execution already jumped to the first matching handler. - D is wrong because
except Exception:is never reached either, and even conceptually,BaseExceptionsits aboveExceptionin the hierarchy -Exceptioninherits fromBaseException, not the other way around, soBaseExceptionis the broader catch.
Memory tip: Think of except clauses like a bouncer line - Python picks the first door that opens, not the best fit. Always order your handlers from most-specific to most-general, or a broad BaseException at the top will swallow everything below it.
Community Discussion
No community discussion yet for this question.