0

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)
4
  • 2
    I'm confused. Don't you want to raise an exception? Commented Oct 29, 2020 at 1:34
  • Your code will start working how you want in about 79 years Commented Oct 29, 2020 at 1:35
  • @DanielWalker I think I know what's confusing him. The sample output doesn't say that the traceback should show the raise line. I think the example is just wrong about that. Commented Oct 29, 2020 at 1:39
  • 1
    The code is correct. Your code outputs what it should, and will be accepted as the answer in this exercise. Commented Oct 29, 2020 at 1:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.