← All lessons

Exceptions: raise

Sign in · Sign up

Lesson 8.0

Usually a function returns a value. But when something unacceptable happens, the function reports an error with raise:

raise ValueError("age cannot be negative")

raise stops the function at that very moment: a return after it does not run, and the error flies up until it is caught with try/except.

Write a function check_age(age) that:

  • returns age if it is not negative;
  • raises a ValueError if the age is negative.
Hint

First the check, then the error, and only then return.

raise goes inside if, so on a bad age the function stops. The error type is ValueError, and the text in the brackets is the one from the task. On a normal age the code reaches the return.