常见异常:
# SyntaxError 语法错误
# NameError: name 'b' is not defined 变量名写错
# IndentationError 缩进错误
# ModuleNotFoundError 第三方包未安装
# FileNotFoundError 文件未找到
# AttributeError: 'int' object has no attribute 'eat' 对象没有某个属性和方法
# IndexError: list index out of range 索引越界
异常捕获:
# try:
# 可能出现异常的代码
# except Exception as e:
# 出现异常时执行的代码
lista=[12,12,12,323,24,0,43,43,54,0,56,565,65,56]
for s in lista:
try:
r=10/s
print(r)
except Exception as e: #Exception 捕获的错误类型 e保存具体错误内容
print("出现错误:",e)
# try:
# 可能出现异常的代码
# except Exception as e:
# 出现异常时执行的代码
# else:
# 没有出现异常时执行的代码
# finally:
# 无论是否出现异常,都会执行的代码(记录日志,关闭资源)
lista=[12,12,12,323,24,0,43,43,54,0,56,565,65,56]
for s in lista:
try:
r=10/s
print(r)
except Exception as e: #Exception 捕获的错误类型 e保存具体错误内容
print("出现错误:",e)
else:
print("正常!")
finally:
print("-----执行完毕!")
自定义异常:
exp=Exception("性别只能是男或者女!") #创建一个异常对象
sex=input("请输入您的性别(男,女)")
if sex=="男" or sex=="女":
print("您输入的性别:",sex)
else:
print("您输入的性别有误!")
raise exp