Python知识分享网 - 专业的Python学习网站 学Python,上Python222
Python 自定义异常类
发布于:2023-09-13 10:00:41

Python 7天快速入门完整视频教程https://www.bilibili.com/video/BV1o84y1Z7J1

 

Python   自定义异常类

 

实际开发中,有时候系统提供的异常类型不能满足开发的需求。这时候你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 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()

 

 

 

转载自: