Lessons 11–15 · About 60 min per lesson
Validation and exceptions
Locate errors at file or row level and report how to correct them.
Lesson breakdown
- Lesson 11
Distinguish missing fields, wrong types and out-of-range values.
- Lesson 12
Use try/except to handle expected numeric conversion failures.
- Lesson 13
Record an invalid row’s line number and reason, then continue.
- Lesson 14
Distinguish a bad row from a failure to read the file.
- Lesson 15
Check that multiple errors do not cause valid rows to be lost.
Worked example
Minutes must be a nonnegative integer. Read the values 12, oops and -3.
How to solve it
Accept 12. The text oops fails conversion, while -3 converts but violates the range. Report the two reasons separately.
Assignment
Write an importer that returns valid records and a list of errors with physical line numbers. The header is on line 1 and no record spans multiple lines.
Check your result
With 12, oops and -3 on lines 2–4, keep 12 and report lines 3 and 4 separately. A value of 0 is valid.