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)

  

猜你喜欢

转载自www.cnblogs.com/Hexdecimal/p/9364477.html