Why Catch Order Matters

Hard ⏱ 18 min 30% acceptance ★★★★★ 4.8
LookupError is the parent of both KeyError and IndexError. Write lookup(container, key) that returns container[key] and classifies failures into 'key-miss' (KeyError), 'index-miss' (IndexError), or 'other-lookup' (any other LookupError) — and get the except order right, because putting the parent first would shadow the children.

Examples

Example 1
Input
lookup({'a': 1}, 'z')
Output
'key-miss'
Explanation

Dict lookups raise KeyError.

Example 2
Input
lookup([1, 2], 9)
Output
'index-miss'
Explanation

List lookups raise IndexError.

Constraints

  • Three except clauses, children before parent.
  • Return the value on success.

Topics

Exception Handlingexception hierarchy

Companies

MicrosoftAdobeOracle

Hints

Hint 1

Most-specific exceptions must come first.

Hint 2

The bare LookupError clause is the safety net.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.