Exceptions & Testing

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, and finally

  • Catch specific exception types and provide a meaningful response to each

  • Raise exceptions with raise and define custom exception classes

  • Apply print-statement debugging and assert to isolate bugs systematically

  • Write doctest examples, unittest test cases, and pytest functions to verify function behavior

  • Explain the difference between type hints, static type checking, runtime validation, and tests

Chapter flow