0%

Errors, Validation, and Debugging · practice

Raise an Error for Invalid Data

The previous lesson checked input before converting it. But a reusable cannot stand beside every caller asking, “Are you sure about that?” It needs to protect its own rule too.

Suppose a function needs a title. Spaces alone do not make a useful title:

def clean_required_title(title):
    clean_title = title.strip()

    if not clean_title:
        raise ValueError("A title cannot be empty")

    return clean_title

The uses truthiness from Chapter 9. After .strip(), an empty is falsy, so not clean_title is true when no text remains.

Raise a specific error

The decisive line is:

raise ValueError("A title cannot be empty")

says that the kind of is acceptable (a string was supplied) but its contents are not suitable here. The text in parentheses explains the rule that was broken.

When Python reaches raise, the current function stops immediately. It does not continue to the below it.

That makes raise different from returning an error message:

  • return gives the caller a normal result;

  • raise reports that the function could not produce a normal result.

Run the valid case, then make it invalid

Run this example once. Then remove Dune from the string and run it again. The second run will show the ValueError and its message.

Try it

Seeing an error here is intentional. For once, the red message is the success case: the function protected its rule instead of quietly returning unusable data.

Put validation before the normal result

The order is important:

  1. clean the title;

  2. check the cleaned title;

  3. raise an error if it is invalid;

  4. otherwise return the valid title.

This keeps the normal path easy to read. The next lesson shows how a caller can catch a specific error and respond to it.

What happens when clean_required_title(" ") reaches the raise line?

Protect a required learner name

The exercise uses the same pattern with a learner name. Clean the text, reject an empty result, and return only a valid name.

Task

Complete clean_required_name(name).

  1. Use .strip() and store the result in clean_name.

  2. If clean_name is empty, raise with the exact message "A name cannot be empty".

  3. Otherwise return clean_name.

Use the empty- truthiness pattern from Chapter 9: if not clean_name:. Keep the example call so the program prints Ada.