Python学习入门笔记(十六)异常处理

注:所有代码部分均为连续的,“结果”为在jupyter分步运行结果

代码部分:

file = open('hahaha','r+')#先去读一个文件,如果能打开的话就可以写入

结果: (报错,因为当前目录下没有此文件,所以异常)

FileNotFoundError Traceback (most recent call last)
<ipython-input-1-91678176fb53> in <module>()
----> 1 file = open('hahaha','r+')#先去读一个文件,如果能打开的话就可以写入

FileNotFoundError: [Errno 2] No such file or directory: 'hahaha'

#处理异常方式
try:#尝试执行这个语句,如果出现异常则保存在Exception 里面
    file = open('hahaha','r+')
except Exception as e:
    print(e)

结果:
[Errno 2] No such file or directory: 'hahaha'

try:
    file = open('hahaha','r+')
except Exception as e:
    print(e)
    response = input('Do you want to create it:')
    if(response=='yes'):
        with open('hahaha','w') as f:
            pass
        print('The file was created successfully')
    else:
        pass

结果:
[Errno 2] No such file or directory: 'hahaha'
Do you want to create it:yes
The file was created successfully

try:
    file = open('hahaha','r+')
except Exception as e:
    print(e)
    response = input('Do you want to create it:')
    if(response=='yes'):
        with open('hahaha','w') as f:
            pass
        print('The file was created successfully')
    else:
        pass
else:#没有错误
    file.write('hahaha')
    file.close()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容