Practice: Multiple Except Blocks

« Read the chapter

Q1. Two handlers

BeginnerCoding

Write code that tries int('a') and prints 'value' for ValueError or 'type' for TypeError.

Goal: Use several except blocks.

Q2. Tuple handler

IntermediateCoding

Write code that runs int(None) and prints 'bad input' for either ValueError or TypeError.

Goal: Group exception types.

Q3. Lookup helper

IntermediateCoding

Write get_item(c, k) that returns c[k] or 'missing' on LookupError. Print get_item([1], 3) and get_item({'a': 2}, 'a').

Goal: Use a parent exception.

Q4. Safe division

IntermediateCoding

Write safe_div(a, b) returning 'zero' on ZeroDivisionError and 'type' on TypeError. Print safe_div(6, 3), safe_div(1, 0), safe_div('a', 2).

Goal: Handle different errors.

Q5. Count error kinds

AdvancedCoding

For items = ['1', 'x', None, '2'] count ValueError and TypeError separately and print both counts as 'v=1 t=1'.

Goal: Count different failures.

Q6. Safety net

AdvancedCoding

Write code that tries [][1] with a ZeroDivisionError handler first and a general Exception handler second; print the class name from the general one.

Goal: Use a general fallback.

Q7. First match

BeginnerOutput

What does this print?

Code
try:
    int('z')
except ValueError:
    print('A')
except Exception:
    print('B')

Goal: Know first match wins.

Q8. Parent first

IntermediateOutput

What does this print?

Code
try:
    {}['k']
except LookupError:
    print('lookup')
except KeyError:
    print('key')

Goal: Order of handlers.

Q9. Tuple match

IntermediateOutput

What does this print?

Code
try:
    1 / 0
except (KeyError, ZeroDivisionError):
    print('caught')

Goal: Tuple handlers.

Q10. Unmatched inner

AdvancedOutput

What does this print?

Code
try:
    try:
        [][0]
    except KeyError:
        print('inner')
except IndexError:
    print('outer')

Goal: Nested handlers.

Q11. Class name

IntermediateOutput

What does this print?

Code
def f(x):
    try:
        return 5 / x
    except ArithmeticError as e:
        return type(e).__name__
print(f(0))

Goal: Hierarchy.

Q12. Return from handler

IntermediateOutput

What does this print?

Code
def f(v):
    try:
        return int(v)
    except ValueError:
        return -1
    except TypeError:
        return -2
print(f('a'), f(None), f('7'))

Goal: Function results.

Q13. Unreachable handler

IntermediateDebugging

This second handler never runs. Fix it so ZeroDivisionError prints zero and others print other.

Code
try:
    1 / 0
except Exception:
    print('other')
except ZeroDivisionError:
    print('zero')

Goal: Order handlers.

Q14. Missing parentheses

IntermediateDebugging

This tuple handler has wrong syntax. Fix it so it prints bad.

Code
try:
    int('q')
except ValueError, TypeError:
    print('bad')

Goal: Group types.

Q15. Wrong parent

AdvancedDebugging

This misses the error. Fix it so it prints lookup.

Code
try:
    [1][5]
except ArithmeticError:
    print('lookup')

Goal: Choose the right parent.

Q16. Repeated code

BeginnerDebugging

These two handlers do the same thing. Combine them so it prints no.

Code
try:
    int('z')
except ValueError:
    print('no')
except TypeError:
    print('no')

Goal: Reduce repetition.

Q17. Which block runs

IntermediateConceptual

If a try raises KeyError and the handlers are LookupError then KeyError, which runs and why?

Goal: Understand matching.

Q18. Hierarchy

BeginnerConceptual

Name two children of LookupError.

Goal: Know the hierarchy.

Q19. One error one handler

BeginnerConceptual

Can two except blocks run for a single error? Explain.

Goal: Know the flow.

Q20. Menu program

IntermediateApplication

A menu program reads a number and picks an item from a list. Which exceptions would you handle and how?

Goal: Apply multiple handlers.