Error Handling – try/except basics, online

Six activities your students do on their own devices. See who's finished, and their scores.

Error Handling – try/except basics in one minute

What students need to know

Naming the exception type catches only that specific kind of error. try/except intercepts errors and lets you handle them gracefully.

Put risky code inside try — if it fails, except handles it. If try succeeds, except is completely skipped.

Mistakes students make

  • Missing colon after try.
  • Missing colon after except.
  • Code inside try must be indented.
  • except cannot stand alone: it must follow a try block.
PREVIOUS · MODULE 21range()
YOU ARE HERE · MODULE 22Error Handling – try/except basics
NEXT · MODULE 23break and continue

Discover other journeys with this module

What students will learn in this module

Every question in Module 22

Quick questions

  1. What does try/except do?ACatches errors so the program doesn't crashBMakes code faster
  2. What goes inside the try block?AError messagesBCode that might cause an error
  3. When does the except block run?AAlwaysBOnly when an error occurs in try
  4. try:\n int('abc')\nexcept:\n print('Oops')\nWhat prints?AOopsBabc
  5. try:\n print(5 + 3)\nexcept:\n print('Error')\nWhat prints?A8BError

Key terms

Students type the meaning of:

  • try
  • except
  • ValueError
  • Error handling

Match the pairs

try:
    x = int('abc')
exept:
    print('oops')
Match it to what it does
except:
    print('error')
try:
    risky()
Match it to what it does
try:
    x = int(val)
except ValueError:
    print('bad')
Match it to what it does
try:
    risky()
except:
    print('handled')
Match it to what it does
try:
    print(int('hi'))
except:
    print('error')
Match it to what it does
try:
    print(int('5'))
except:
    print('error')
Match it to what it does

Fill in the blanks

  1. ___:
        num = int(input('Number: '))
    except:
        print('Invalid')
  2. try:
        num = int(input('Number: '))
    ______:
        print('Invalid')
  3. try:
        num = int(input('Number: '))
    except __________:
        print('Not a number')
  4. try:
        result = 10 / _
    except:
        print('Error')
  5. try:
        x = ___(input('Enter num: '))
    except:
        print('Bad input')

Spot the error

Question 1

AtryB    num = int(input('Number: '))Cexcept:D    print('Invalid')

Question 2

Atry:B    num = int(input('Number: '))CexceptD    print('Invalid')

Question 3

Atry:Bnum = int(input('Number: '))Cexcept:D    print('Invalid')

Question 4

Aexcept:B    print('Invalid')C    print('Try again')Dprint('Done')

Question 5

ATry:B    num = int('abc')CExcept:D    print('Error')