python -异常处理/自定义异常类


#异常处理

try:
xxxx 可能发生错误逻辑语句
except:
xxx 报错后处理
else:
xxx 没发生错误语句
finally
xxx 不管有没有错都执行


-- 名称异常(NameError):变量未定义。
-- 类型异常(TypeError):不同类型数据进行运算。
-- 索引异常(IndexError):超出索引范围。
-- 属性异常(AttributeError):对象没有对应名称的属性。
-- 键异常(KeyError):没有对应名称的键。
-- 为实现异常(NotImplementedError):尚未实现的方法。
-- 异常基类Exception。


raise 语句:人工抛出异常


自定义异常类
class WeightError(Exception):
def __init__(self, message="", code="", id=0):
# super().__init__()
self.message = message
self.code = code
self.id = id


class Wife:
def __init__(self, name="", weight=0):
self.name = name
self.weight = weight

@property
def weight(self):
return self.__weight

@weight.setter
def weight(self, value):
if 20 <= value <= 200:
self.__weight = value
else:
# 有意抛出异常
# 传递的错误信息:错误原因,错误代码,错误编号,.....
# raise Exception("体重超过范围")
raise WeightError("体重超过范围", "if 20 <= value <= 200", 1001)

猜你喜欢

转载自www.cnblogs.com/chenlulu1122/p/11921774.html