Python自定义异常

  1. 自定义异常类
  2. 抛出异常
  3. 捕获异常
# 继承异常类Exception
class ShortPassword(Exception):
    def __init__(self,length,min_length):
        self.length = length
        self.min_length = min_length

    def __str__(self):
        return f'你的密码长度是{self.length},最小长度为{self.min_length}'


def Password():
    password = input('请输入密码')
    try:
        if len(password) <= 3:
            # 抛出异常
            raise ShortPassword(len(password),3)
    except Exception as result:
        print(result)
    else:
        print('密码已输入')

Password()

posted @ 2021-03-09 16:30  code-G  阅读(116)  评论(0编辑  收藏  举报