Python基础——try(异常处理)

1.try…except…

输出错误:try:, except … as …: 看如下代码

try:
    file = open('example','r')  #如果没有文件,将执行except 
except Exception as e:     #将报错存储在 e 中
    print(e)

#输出
[Errno 2] No such file or directory: 'example'

2.try…except…else

处理错误:会使用到循环语句。首先报错:没有这样的文件No such file or directory. 然后决定是否输入y, 输入y以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入abcd

try:
    file = open('example_1','r+')
except Exception as e:
    #print(e)
    print('No such file!')
    response = input('would you like to create a new file:')
    if response == 'y':
        file = open('example_1','w')     #如果输入y,将创建一个文件
    else:
        pass    #输入不是y,则什么也不干
else:
    file = open('example_1','w')  
    file.write('abcd')
    file.close()
finally:
    print('over!')

#输出
No such file!
would you like to create a new file:y
over!

将会在同级目录下看到文件example_1中有“abcd”
在这里插入图片描述

发布了173 篇原创文章 · 获赞 505 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/105127240