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

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

代码部分:

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

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

FileNotFoundError Traceback (most recent call last)
in ()
----> 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()

你可能感兴趣的:(Python学习入门笔记(十六)异常处理)