Practice: try and except

« Read the chapter

Q1. Safe conversion

BeginnerCoding

Write code that tries int('12x') and prints 'bad number' if it fails.

Goal: Write try and except.

Q2. Default on failure

IntermediateCoding

Write a function parse(text) that returns int(text) or -1 if it fails. Print parse('5') and parse('five').

Goal: Return defaults safely.

Q3. Missing key message

BeginnerCoding

Given d = {'a': 1}, try d['z'] and print 'no such key' on KeyError.

Goal: Catch KeyError.

Q4. Sum valid numbers

IntermediateCoding

For items = ['1', 'x', '3', 'y', '5'] add up the ones that convert and print the total.

Goal: Use try in loops.

Q5. Print the error

IntermediateCoding

Try 10 / 0 and print the exception message.

Goal: Use the error object.

Q6. Input loop

AdvancedCoding

Given the inputs, simulate with a list: for text in ['no', '8']: print 'retry' if it is not a number, otherwise print the number and stop.

Goal: Build an input loop.

Q7. Skipped line

BeginnerOutput

What does this print?

Code
try:
    print('one')
    int('x')
    print('two')
except ValueError:
    print('three')
print('four')

Goal: Trace try flow.

Q8. No error

BeginnerOutput

What does this print?

Code
try:
    print('go')
except ValueError:
    print('error')
print('done')

Goal: Know when except is skipped.

Q9. Wrong handler

IntermediateOutput

What does this print?

Code
try:
    try:
        int('x')
    except KeyError:
        print('key')
except ValueError:
    print('value')

Goal: Match exception types.

Q10. Function default

IntermediateOutput

What does this print?

Code
def f(t):
    try:
        return int(t)
    except ValueError:
        return 0

print(f('4') + f('a'))

Goal: Follow return values.

Q11. Error name

IntermediateOutput

What does this print?

Code
try:
    [][0]
except Exception as e:
    print(type(e).__name__)

Goal: Name exceptions.

Q12. Counting failures

AdvancedOutput

What does this print?

Code
bad = 0
for t in ['1', 'a', '2', 'b', 'c']:
    try:
        int(t)
    except ValueError:
        bad += 1
print(bad)

Goal: Trace a loop with try.

Q13. Fix the bare handler

IntermediateDebugging

This handler hides every bug. Fix it to catch only the expected error and print 'bad'.

Code
try:
    int('q')
except:
    pass

Goal: Avoid bare except.

Q14. Fix the indentation

BeginnerDebugging

This code has a syntax problem. Fix it so it prints ok.

Code
try:
print(int('3'))
except ValueError:
print('bad')

Goal: Write correct syntax.

Q15. Fix the wrong type

IntermediateDebugging

This does not catch the error. Fix it so it prints bad.

Code
try:
    int('z')
except KeyError:
    print('bad')

Goal: Use the right type.

Q16. Use the error later

AdvancedDebugging

The variable e is used after the except block and fails. Fix it to print the message.

Code
try:
    int('z')
except ValueError as e:
    pass
print(e)

Goal: Understand scope of e.

Q17. What if no error

BeginnerConceptual

Explain what Python does with the except block when the try block finishes without error.

Goal: Know the flow.

Q18. Why avoid bare except

IntermediateConceptual

Give two reasons why except: is a poor choice.

Goal: Avoid bad habits.

Q19. Small try block

IntermediateConceptual

Why should a try block be kept small?

Goal: Write focused try blocks.

Q20. Age form

IntermediateApplication

A form asks for age. Describe how try and except can keep it from crashing when the user types 'abc'.

Goal: Validate input.