• 技术文章 >Python技术 >Python基础教程

    python用户如何自定义异常

    小妮浅浅小妮浅浅2021-08-20 17:41:06原创5865

    说明

    1、程序可以通过创建一个新的异常类来命名它们自己的异常。

    异常应该是典型的继承自Exception类,直接或间接的方式。

    2、异常python有一个大基类,继承了Exception。因此,我们的定制类也必须继承Exception。

    实例

    class ShortInputException(Exception):
        def __init__(self, length, atleast):
            self.length = length
            self.atleast = atleast
    def main():
        try:
            s = input('请输入 --> ')
            if len(s) < 3:
                # raise引发一个你定义的异常
                raise ShortInputException(len(s), 3)
        except ShortInputException as result:#x这个变量被绑定到了错误的实例
            print('ShortInputException: 输入的长度是 %d,长度至少应是 %d'% (result.length, result.atleast))
        else:
            print('没有异常发生')
    main()

    以上就是python用户自定义异常的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python自定义异常
    品易云
    上一篇:python编写程序的常见错误 下一篇:python thread模块创建线程

    相关文章推荐

    • python中socket如何建立服务器• python中socket建立客户连接• python中Roberts算子是什么• python中Prewitt算子如何理解• python中Sobel算子是什么• python中Sobel算子如何使用• python中Laplacian算子如何使用• python中Laplacian算子是什么• python输入函数input的使用• python控制语句的两大分类• python编写程序的常见错误

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网