抛出自定义的异常
在开发中,除了代码执行出错Python解释器会抛出异常之外,还可以根据应用程序特有的业务需求主动抛出异常。
设计一个人类,有名字(name)和年龄(age)两个属性,按照业务需求,如果年龄(age)的范围在(0,150]完成对象的创建,反之将抛出异常,终止程序。
# 自定义一个人类 class Person(object): def __init__(self, name, age): # 如果年龄满足需求 if 0 < age <= 150: self.name = name self.age = age else: # 如果条件不满足需求 # 将抛出异常,终止程序 pass
Python中提供了一个Exception异常类,Exception异常类是所有异常类的父类,在开发时,如果满足特定业务需求时,希望抛出异常,可以如下操作:
- 创建一个继承于Exception异常类的自定义异常对象;
- 使用 raise 关键字抛出自定义异常对象;
# 自定义异常类 class AgeError(Exception): def __init__(self, age): # 保存年龄,进行私有 self.__age = age # 设计异常的信息描述 def __str__(self): return "传入的年龄超出的正常范围:age=%d" % self.__age # 自定义一个人类 class Person(object): def __init__(self, name, age): # 如果年龄满足需求 if 0 < age <= 150: self.name = name self.age = age else: # 如果条件不满足需求 # 将抛出异常,终止程序 raise AgeError(age) # 测试 xm = Person("小明", 151) # 控制台输出: __main__.AgeError: 传入的年龄超出的正常范围:age=151
例子:
# 自定义异常类 class AgeError(Exception): def __init__(self, age): self.__age = age # 重写str方法 def __str__(self): return "您传入的年龄不满足需求:age=%d" % self.__age # 自定义一个人类 class Person(object): def __init__(self, name, age): # 判断年龄 if 0 < age <= 150: self.name = name self.age = age else: # 抛出自定义异常 raise AgeError(age) xm = Person("小明", 160)