1, the common abnormal
1) In addition to the operational 0 --ZeroDivisionError
2) can not find the file readable --FileNotFoundError
. 3) the value of the error --ValueError
. 4) indexing error --IndexError
. 5) type error --TypeError
. 6) the error variable name --NameError
2, exception handling
. 1) try_except
① single branch
x = 10
y = 0
try:
z = x/y
except ZeroDivisionError:
print("0不能作除数")
② multi-branch
ls = []
d = {"name":"LC"}
try:
d["age"]
except NameError:
print("变量名不存在")
except IndexError:
print("索引超出界限")
except KeyError:
print("键不存在")
③ abnormal Universal Exception
ls = []
d = {"name":"LC"}
try:
d["age"]
except Exception:
print("出错了")
④ capture value as abnormal
ls = []
d = {"name":"LC"}
try:
y = m
d["age"]
except Exception as e: # 获取错误的值
print(e)
2)try_except_else
try:
with open("try.txt") as f:
text = f.read()
except FileNotFoundError:
print("找不到文件")
else:
print("找到了")
3) try_except_finally: regardless of whether the try block execution, finally finally will be executed
ls = []
d = {"name":"LC"}
try:
y = x
ls[3]
d["age"]
except Exception as e: # 获取错误的值
print(e)
finally:
print("执行finally")