10. Exceptions & Testing#
Errors are inevitable in any program. Python distinguishes two major categories: exceptions (runtime errors that interrupt execution) and semantic errors (silent bugs where code runs but produces the wrong answer). This chapter teaches you to handle both:
exception handling lets your program recover gracefully from runtime failures;
debugging and testing techniques help you find and eliminate logic errors before they reach users.
Learning goals: By the end of this chapter you will be able to:
Distinguish between syntax errors, runtime errors, and semantic errors
Read and interpret Python tracebacks to locate the source of a bug
Handle exceptions gracefully with
try,except,else, andfinallyCatch specific exception types and provide a meaningful response to each
Raise exceptions with
raiseand define custom exception classesApply print-statement debugging and
assertto isolate bugs systematicallyWrite
doctestexamples,unittesttest cases, andpytestfunctions to verify function behaviorExplain the difference between type hints, static type checking, runtime validation, and tests