Python----面向对象---主动触发异常-raise
主动触发异常-raise
1 class People: 2 def __init__(self, name, age): 3 if not isinstance(name, str): 4 raise TypeError('名字必须是str类型') 5 if not isinstance(age, int): 6 raise TypeError('年龄必须是int类型') 7 8 self.name = name 9 self.age = age 10 11 p = People('abc', '123') 12 13 结果为: 14 15 Traceback (most recent call last): 16 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/33 try...except详细用法.py", line 59, in <module> 17 p = People('abc', '123') 18 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/33 try...except详细用法.py", line 54, in __init__ 19 raise TypeError('年龄必须是int类型') 20 TypeError: 年龄必须是int类型