61-自定义异常
作者:互联网
def set_age(name,age): if not 0 < age < 80: raise ValueError('年龄超过范围') # 自主决定触发什么样的异常 print("%s is %d years old" % (name,age)) def set_age2(name,age): assert 0 < age < 80, '年龄超过范围' # 断言异常 print("%s is %d years old" % (name,age)) if __name__ == '__main__': set_age('xiaoming',50) set_age2('xiaohong', 90)
结果输出:
Traceback (most recent call last): File "F:/20180731桌面/CMDB/CMDB/test/Python_test.py", line 984, in <module> set_age2('xiaohong', 90) File "F:/20180731桌面/CMDB/CMDB/test/Python_test.py", line 979, in set_age2 assert 0 < age < 80, '年龄超过范围' # 断言异常 AssertionError: 年龄超过范围 xiaoming is 50 years old
标签:__,set,name,自定义,age,age2,61,test,异常 来源: https://www.cnblogs.com/hejianping/p/10954329.html