Error Handling – try/except basics, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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
What students will learn in this module
Every question in Module 22
Quick questions
- What does try/except do?ACatches errors so the program doesn't crashBMakes code faster
- What goes inside the try block?AError messagesBCode that might cause an error
- When does the except block run?AAlwaysBOnly when an error occurs in try
- try:\n int('abc')\nexcept:\n print('Oops')\nWhat prints?AOopsBabc
- try:\n print(5 + 3)\nexcept:\n print('Error')\nWhat prints?A8BError
Key terms
Students type the meaning of:
tryexceptValueErrorError handling
Match the pairs
try:
x = int('abc')
exept:
print('oops')Match it to what it doesexcept:
print('error')
try:
risky()Match it to what it doestry:
x = int(val)
except ValueError:
print('bad')Match it to what it doestry:
risky()
except:
print('handled')Match it to what it doestry:
print(int('hi'))
except:
print('error')Match it to what it doestry:
print(int('5'))
except:
print('error')Match it to what it doesFill in the blanks
___: num = int(input('Number: ')) except: print('Invalid')try: num = int(input('Number: ')) ______: print('Invalid')try: num = int(input('Number: ')) except __________: print('Not a number')try: result = 10 / _ except: print('Error')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')
