异常
常见异常 :
- assertionError assert (后面条件为假)
- attributeError (尝试访问未知的对象属性)
- index Error (索引超出序列范围)
- keyError (字典中找到不存在的关键字)
- osError (操作系统产生的异常)
- nameError (尝试访问一个不存在的变量)
- synataxError python (语法错误)
- typeError (不同类型之间的无效操作)
- zerodivisionError (除零错误)
try:
with open("none.txt", "r", encoding = "utf-8") as f:
print(f.read())
except OSError as reason:
print("error ", str(reason)) #error [Errno 2] No such file or directory: 'none.txt'
try:
a=int(input("请输入一个数"))
result=8/a
print(result)
except ValueError as reason: #输入不是数字
print("error ", str(result))
except Exception as reason: #输入0
print("annoymouse error %s"%str(reason))
except Exception as result: #二者都是捕获所有异常, 是等价的
print("some error %s" %result)
except:
print("some error")
else:
print("none error")
finally:
print("dont care error")
异常的传递
def func1():
print("func1 start")
1/0
print("func1 end")
def func2():
print("func2 start")
func1()
print("func2 end")
def main():
try:
func2()
except Exception as op:
print(op)
main()
# func2 start
# func1 start
# division by zero