So I'm experimenting making my own program. I have the user input a string and an integer (name, age).
I want to raise a Value Error if the age is under 1 (if age > 1:) I did that. But I'm not sure what to do if the name is not a string. Is it a TypeError and can two types of errors be raised at the same time? If so how?
Probably got some terminology wrong but having trouble thinking right now.
Here's the code:
# This program asks name how old you are and makes exceptions to check and see if
there are errors
def hogwarts_express (name, age):
if age < 1:
raise ValueError ("Error: Apparently you don't exist. Please pick a number older
than 0!")
if int (age) >= 10:
print ("Hello {}! Welcome to the Hogwarts Express, your old enough to go now.
Here 's your ticket!".format(name))
else:
print ("Sorry {} you're not old enough to board the express.".format(name))
try:
your_name = input("What's your name? ")
age = int(input("How old might you be? "))
together = hogwarts_express (your_name, age)
except ValueError as err:
print ("That's not a valid value. Please input something else.")
print ("{}".format(err))
else:
print (together)
There's really no need to raise two exceptions simultaneously. It's fine to raise the first error you detect. Yes, a TypeError
is appropriate if you expected a string but got something else. You can do the check and raise the TypeError
either before or after the ValueError
. You can catch multiple exception types in the same try
statement by adding more except
clauses.
Another option is to use an assert
statement to validate all the arguments. An assertion indicates that a violation is a bug in the program, and you don't want to recover by using a try
statement.
I should mention that it is possible to chain exceptions in Python (using the raise ... from ...
syntax), but this used when translating from one exception type to another or for when one exception causes another, which does not seem to apply to this case.
Update: PEP 654 adds exception groups and except*
as of Python 3.11. Still probably overkill for this case, but it is possible now.