Python 自定义异常类

视频版教程 Python3零基础7天入门实战视频教程

实际开发中,有时候系统提供的异常类型不能满足开发的需求。这时候你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类,可以直接继承,或者间接继承。

# 自定义异常类
class TooLongException(Exception):

    def __init__(self, length):
        self.lenght = length

    def __str__(self):
        return f"长度是{self.lenght},超长了"


def name_test():
    try:
        name = input("请输入您的姓名:")
        if len(name) > 4:
            raise TooLongException(len(name))
        else:
            print(name)
    except TooLongException as tle:
        print("出现异常,", tle)


name_test()

你可能感兴趣的:(Python,python)