try:
f= open("D:/abc.txt","r",encoding="UTF-8")
except:
print("出现异常了,因为文件不存在,我将open的模式,改为w模式去打开")
f =open("D:/abc.txt","w",encoding="UTF-8")
解释:以只读模式打开不存在的文件程序会报错,所以在异常处理中用写模式打开该文件,因为写模式,文件不存在会创建文件。
以下代码,列举了常见异常类型,比如变量未定义异常,除零异常等,也可以利用()捕捉多个可能出现的异常,未正确设置捕获异常类型,将无法捕获异常。
try:
print(num)
except NameError as e:
print("出现了变量未定义的异常")
print(e)
try:
1/0
except ZeroDivisionError as e:
print("出现了除0异常")
print(e)
try:
1/0
print(num)
except (ZeroDivisionError,NameError) as e:
print("出现了除0异常或变量未定义异常")
print(e)
# 捕获所有异常
try:
f = open("D:/123.txt","r")
except Exception as e:
print("出现异常了")