Skip to the content

Raising errors

Python · Unit 9: Errors and exceptions

raise throws an error on purpose. It's for when data arrives that makes no sense: better to stop with a clear message than to carry on and give a wrong result.

You write the error type and, in parentheses, the message.

def area(side):
    if side < 0:
        raise ValueError("side < 0")
    return side * side

print(area(3))

Prints

9

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Multiple choice

    What happens with area(-2)?

  2. 2. Predict the output

    as e works with Python's own errors too. What does it print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    Complete it so withdrawing more than there is warns you with an error.

  5. 5. Multiple choice

    average(grades) gets an empty list. Which line warns best?

  6. 6. Find the bug

    validate should reject ages below 0 or above 120. Which line has the bug?

  7. 7. Multiple choice

    What does this function do?

  8. 8. Put the lines in order

    Put the program in order. pay rejects amounts of 0 or less, and the try catches the warning.

  9. 9. Write the code

    Add an if to tickets that raises ValueError("no tickets") when n is less than 1.

  10. 10. Predict the output

    Here the try is outside the for. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →