Reputation: 1
In this exercise, you'll raise a manual exception when a condition is not met in a particular function. In particular, we'll be converting birth year to age.
Specifications One a new cell in your notebook, type the following function
import datetime
class InvalidAgeError(Exception):
pass
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
return age
Add a check that tests whether or not the person has a valid (0 or greater) If the age is invalid, raise an InvalidAgeError Expected Output
>>> get_age(2099)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.InvalidAgeError
My code is as following, but it shows error on raise line, how can i get expected output?
import datetime
class InvalidAgeError(Exception):
pass
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
if age >=0:
return age
else:
raise InvalidAgeError
get_age (2099)
Upvotes: 0
Views: 793
Reputation: 1873
As mentioned in the comments, your code is correct. I guess you would like to see the error message that explains why the error is raised. Here is the code for it.
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
if age >=0:
return age
else:
raise InvalidAgeError(f'InvalidAgeError: the birthyear {birthyear} exceeds the current year ({datetime.datetime.now().year})')
Please feel free to modify the Exception message the way you find appropriate.
Upvotes: 1