Errors, Validation, and Debugging · practice
Raise an Error for Invalid Data
The previous lesson checked input before converting it. But a reusable
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 .strip(), an empty not clean_title is true when no text remains.
Raise a specific error
The decisive line is:
raise ValueError("A title cannot be empty")
When Python reaches raise, the current function stops immediately. It does not continue to the
That makes raise different from returning an error message:
returngives the caller a normal result;raisereports 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.
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:
clean the title;
check the cleaned title;
raise an error if it is invalid;
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).
Use
.strip()and store the result inclean_name.If
clean_nameis empty, raisewith the exact message "A name cannot be empty".Otherwise return
clean_name.
Use the empty-if not clean_name:. Keep the example call so the program prints Ada.