一、自定义异常应用场景:
- 在开发中,除了 代码执行出错 Python 解释器会 抛出 异常之外
- 还可以根据 应用程序 特有的业务需求 主动抛出异常
二、语法格式:
关键词—raise
def register():
username = input("username:")
password = input("password:")
if len(password) >= 8:
print(f"{username}:{password}")
else:
# 创建异常
ve = ValueError("密码长度不足8位")
# 抛出异常
raise ve
if __name__ == '__main__':
register()
三、案例练习:
需求
- 编写一个函数,接收姓名和年龄,如果年龄不在1到120之间,产生 ValueError 异常
def get_info(name, receive_age):
try:
a = int(receive_age)
except Exception as e:
print(e)
else:
if a < 1 or a > 120:
raise ValueError("年龄必须在1到120之间")
finally:
print(f"username:{name},age:{a}")
if __name__ == '__main__':
username = input("username:")
age = input("age:")
get_info(username, age)
网友评论