python3 Exception自定义异常类
程序员文章站
2024-03-20 18:55:16
...
1.自定义异常类
2.抛出异常
3.捕获异常
1.
class Error(Exception):
def __init__(self,length,min_length):
self.length = length
self.min_len = min_length
# 异常描述信息
def __str__(self):
return f'你输入的长度是{self.length},不能少于{self.min_len}'
def main():
try:
con = input('请输入密码: ')
if len(con)<3:
# 抛出异常
2.
raise Error(len(con),3)
# 捕获异常
3.
except Exception as result:
print(result)
else:
print("输入完成")
main()