Raising an Error
So far, Python has raised the exceptions. You can raise one yourself, with raise. That's useful in your own function, when it gets data that make no sense. Remember the function for the price of a zoo ticket from the lesson on functions? Here, a negative age raises a ValueError:
def ticket_price(age):
if age < 0:
raise ValueError("The age can't be negative.")
if age < 6:
return 0
if age < 18:
return 5
return 10
print(ticket_price(30))
print(ticket_price(-3))10
Traceback (most recent call last):
File "<exec>", line 11, in <module>
File "<exec>", line 3, in ticket_price
ValueError: The age can't be negative.raise ValueError("The age can't be negative.") creates a ValueError with your message and raises it. From there on, it works like the exceptions that Python raises: the function stops right away (as with return, the rest of it doesn't run), and unless something catches the exception, the program ends with a traceback. Its last line is your type and your message, and the line above it shows where you raised it.
Why not print a message and return something, such as 0? Because the code that called the function couldn't tell. A ticket for 0 looks like the free ticket of a small child, and the program would go on with a wrong price. An exception can't be overlooked: the code that calls the function either catches it and deals with the problem, or the program stops and shows where.
Pick the type that fits the problem. A ValueError is for a value of the right type that makes no sense, such as a negative age or a username that is too short, and it's the one you'll raise most often. Write the message for the person who will read it: say what's wrong.
A typical mistake is to leave out the type: raise "The age can't be negative." ends with TypeError: exceptions must derive from BaseException, because only an exception can be raised, not a text.
Instructions
- 1
The code below the function calls
check_username()in atryblock and prints the message of aValueError. On this website, a username needs at least 3 characters. Incheck_username(), before thereturn, raise aValueErrorwith the messageThe username is too short.whennamehas fewer than 3 characters. The program then printsSorry: The username is too short.The exercise also tries other usernames in place of"Al", so keep that line. - 2
A username must not contain spaces either. Add a second check: when there's a space in
name, raise aValueErrorwith the messageThe username must not contain spaces.Try it with"max power"in place of"Al", and then change it back.