Skip to course content
Free course

Python Foundations / Module 6 / Raising Useful Errors

Module 6 lesson

Raising Useful Errors

Unit ID: M06-U05 Estimated active time: 20-30 minutes

Stop when the contract is broken

Use raise when a function cannot produce a valid result under its stated contract.

if type(raw_hours) not in (int, str):
    raise TypeError("hours must be an integer or integer text")

Use exception types meaningfully:

  • TypeError: wrong kind of value;
  • ValueError: suitable general type, but unacceptable content or range;
  • KeyError: required mapping key is absent when accessed directly.

Write actionable messages

Weak:

raise ValueError("bad input")

Stronger:

raise ValueError("hours must be from 0 to 40")

The stronger message states the violated rule without exposing sensitive data.

Preserve the original cause when translating

try:
    hours = int(raw_hours.strip())
except ValueError as error:
    raise ValueError("hours text must contain a whole number") from error

Exception chaining records that the clearer domain message came from the conversion failure.

Do not use assertions for user-input validation

Assertions describe conditions that should hold during correct program operation. They can be disabled in some execution modes. Use explicit checks and raised exceptions for invalid external input.

Practice

Improve these messages:

  • wrong for a non-string course code;
  • no for an empty code;
  • invalid for hours above 40.

Choose TypeError or ValueError and explain the choice.

Takeaway

Raise an exception when the function cannot honour its contract. Choose a meaningful type and an actionable, non-sensitive message. Next, tests will prove that both valid results and intended failures remain stable.