简体   繁体   English

在 Python 中引发异常类

[英]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添加一个检查该人是否具有有效的(0 或更大)如果年龄无效,则引发 InvalidAgeError 预期输出

>>> 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?我的代码如下,但它在 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)

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.请随意以您认为合适的方式修改异常消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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