Raising exceptions

raise ValueError("message") stops the function and hands the error to the caller. Pick the built-in type that fits:

  • ValueError: right type, bad value (parse_age("-4")).
  • TypeError: wrong type altogether.
  • KeyError, IndexError: something isn't there.
  • NotImplementedError: a method a subclass must still write.

Make the message say what was wrong and show the bad value with !r. "age must be 0 to 150, got -4" saves the next person a debugging session.

Inside an except, a bare raise re-raises the same exception with its traceback intact. Use it when you only want to log or add context.

raise NewError(...) from e swaps in a clearer error but keeps the original as e.__cause__. Tracebacks then show both, joined by "The above exception was the direct cause".

Run it, then remove from e and compare cause.