Python知识点8:错误与异常处理
b站学习:https://www.bilibili.com/video/BV12E411A7ZQ
一、异常简介
1.捕获异常
IOError异常
#捕获异常
try:
print("前")
f=open("123.txt","r") #文件不存在,会出现FileNotFoundError
print("后") #pass:不会被执行
except IOError: #文件没找到属于IOError
pass
NameError异常
try:
print(num) #num没有声明
except NameError:
print("产生错误了")
捕获多种异常并获取错误信息
try:
print("前")
f=open("123.txt","r") #文件不存在,会出现FileNotFoundError
print("后") #中断了,不会被执行
print(num) #中断了,不会被执行
except (IOError,NameError) as result: #将所有有可能发生的异常写出来
print("产生错误了")
print(result) #获取错误信息
捕获所有异常
try:
print("前")
f=open("123.txt","r") #文件不存在,会出现FileNotFoundError
print("后") #中断了,不会被执行
print(num) #中断了,不会被执行
except Exception as result: #Exception表示所有可能出现的异常
print("产生错误了")
print(result) #获取错误信息
嵌套以及finally
#嵌套
import time
try:
f=open("test.txt","r")
try:
while True:
content=f.readline()
if len(content)==0:
break
time.sleep(2)
print(content)
finally: #一定会被执行
f.close()
print("文件关闭")
except Exception as result:
print("发生异常")
#课后练习
def writeFile(f):
poem=input("请输入古诗词")
f.write(poem)
def copyFile(a,b):
content=a.readlines()
for i in content:
b.write(i)
f=open("gushi.txt","w",encoding="utf-8")
writeFile(f)
f.close()
f=open("gushi.txt","r",encoding="utf-8")
g=open("copy.txt","w",encoding="utf-8")
copyFile(f,g)
f.close()
g.close()