• Python入门学习笔记9(自定义异常与断言)


    自定义异常

    自定义一个继承自Exception的类,在类中定义__str__(self)返回自定义的异常信息,然后便可以通过raise抛出这种自定义异常,捕获处理和普通的异常完全一样

    class SelfException(Exception):
        def __init__(self,msg):
            self.msg = msg
    
        def __str__(self):
            return self.msg
    
    def throwException():
        i = 0
        if i == 0:
            raise SelfException("自定义错误")
    
    try:
        throwException()
    except SelfException as e:
        print(e)

    断言

    通过assert(断言)可以简单地实现数据检验,不通过直接抛出异常的操作

    #断言的作用是数据的校验,检验错误时会抛出AssertionError
    data = "12345"
    
    #类型是str,通过
    assert type(data) is str
    print("%s is str" %data)
    #类型不是int,抛出异常
    assert type(data) is int
    print("%s is int" %data)
    

      

  • 相关阅读:
    五种I/O模型
    Python socket服务
    Python 协程
    python openpyxl 简单使用
    python 文件夹压缩
    Python 多进程
    MySQL 自定义函数
    python 队列
    python 多线程、线程锁、事件
    python paramiko模块:远程连接服务器
  • 原文地址:https://www.cnblogs.com/Hexdecimal/p/9364477.html
Copyright © 2020-2023  润新知