Intermediate level · Module 2 of 6 · 14 guided hours
Error Handling and Defensive Programming
Make programs robust against bad input, missing files and unexpected data, and record what went wrong.
Learning objectives
- Catch and handle exceptions with try/except/else/finally
- Validate input and raise meaningful errors
- Record program activity with the logging module
Topics
- exception types
- try/except/else/finally
- raising exceptions
- input validation
- logging
Lessons
-
Lesson 1 Handling Exceptions
Catch specific errors so a program can recover or explain the problem instead of crashing.
exceptionValueError/FileNotFoundErrortry/exceptfinally
-
Lesson 2 Validating Data and Raising Errors
Check data against rules and raise clear errors when it is invalid.
validation ruleraisecustom error messagefail fast
-
Lesson 3 Logging Program Activity
Replace scattered print statements with the logging module so problems can be investigated later.
logging levelslog filebasicConfigaudit trail
Practical activity
Harden a fragile script supplied by the instructor so it survives ten deliberately broken input files, logging every problem.
Expected outcomes
- Programs that fail gracefully and explain why
- A habit of validating data before using it
Assessment
Instructor runs the hardened script against hidden broken files; marks for no crashes and accurate log entries.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.