简体   繁体   中英

raise exception class in Python

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM