Files – Error Handling (try/except), online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
Files – Error Handling (try/except) in one minute
What students need to know
Catching FileNotFoundError specifically handles the most common file error. The finally block runs whether or not an exception occurred — great for cleanup.
FileNotFoundError is specific to missing files — ValueError is for bad values. Files are outside your program's control — they can be missing, locked, or unreadable.
Mistakes students make
- Missing colon after try.
- Error names are capitalized: FileNotFoundError.
- try must come before except.
- Python uses except, not catch.
PREVIOUS · MODULE 46File Operations – Write
YOU ARE HERE · MODULE 47Files – Error Handling (try/except)
NEXT · MODULE 48Creating Modules (.py files to import)
What students will learn in this module
Every question in Module 47
Quick questions
- What error occurs when reading a missing file?AFileNotFoundErrorBValueError
- Why use try/except with files?AFiles might not exist or be inaccessibleBIt makes code faster
- What does 'finally' do?AOnly runs on errorBAlways runs, even if there's an error
- Which is safer: try/except or with?ABoth together is safestBtry/except alone
- What error if you can't write to a file?AWriteErrorBPermissionError
Key terms
Students type the meaning of:
FileNotFoundErrorPermissionErrorfinally:except ___Error:
Match the pairs
open('missing.txt')Match it to what it doestry:
f = open('f.txt')
except:
pass
f.read()Match it to what it doestry:
f = open('f.txt')
except FileNotFoundError:
print('Not found')Match it to what it doestry:
open('f.txt')
finally:
print('done')Match it to what it doestry:
open('x.txt')
except FileNotFoundError:
print('Missing')Match it to what it doestry:
open('x.txt')
except Exception as e:
print(type(e).__name__)Match it to what it doesFill in the blanks
try: with open('f.txt') as f: print(f.read()) except _________________: print('Not found')try: with open('f.txt') as f: print(f.read()) except Exception __ e: print(e)___: f = open('f.txt') except FileNotFoundError: print('Missing')try: with open('f.txt') as f: print(f.read()) except _______________: print('No access')try: open('f.txt') except FileNotFoundError: print('Missing') _______: print('Done')
Spot the error
Question 1
AtryB with open('f.txt') as f:C print(f.read())Dexcept FileNotFoundError:E print('Missing')
Question 2
Atry:B with open('f.txt') as f:C print(f.read())Dexcept filenotfounderror:E print('Missing')
Question 3
Aexcept:B print('Error')Ctry:D with open('f.txt') as f:E print(f.read())
Question 4
Atry:B with open('f.txt') as f:C print(f.read())Dcatch FileNotFoundError:E print('Missing')
Question 5
Atry:B with open('f.txt') as f:C print(f.read())Dexcept:E pass # silently ignore
