在某些特定环境下, 主动抛出可能的异常, 给调用者处理, 增加程序的健壮性
需要使用 raise 抛出一个异常对象, 异常对象可以使用str作为异常描述
主动抛出异常实例
def input_password():
pwd = input("请输入密码")
if len(pwd) >= 8:
return pwd
ex = Exception("pwd len less then 8")
raise ex
try:
pwd = input_password()
print(pwd)
except Exception as ex:
print("异常描述:"+str(ex))
程序运行的输入输出结果如下:
请输入密码ab
异常描述:pwd len less then 8