在Python中引发异常类

2024-09-29 17:50:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在本练习中,您将在特定函数中不满足条件时引发手动异常。特别是,我们将把出生年份转换为年龄

规格 在笔记本中的一个新单元中,键入以下函数

 import datetime

 class InvalidAgeError(Exception):
    pass

 def get_age(birthyear):
    age = datetime.datetime.now().year - birthyear
    return age

添加一项检查,以测试此人是否拥有有效的(0或更高) 如果年龄无效,请提出无效错误 预期产量

>>> get_age(2099)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.InvalidAgeError

我的代码如下所示,但它在raise行上显示错误,如何获得预期的输出

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)

Tags: 函数importagegetdatetimereturndefexception
1条回答
网友
1楼 · 发布于 2024-09-29 17:50:56

如注释中所述,您的代码是正确的。我猜您希望看到解释产生错误原因的错误消息。这是它的代码

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})')

请随意以您认为合适的方式修改异常消息

相关问题 更多 >

    热门问题