Try except finally raise

try:
#    int('qwe')
    f = open('我为什么是一个文件.txt','w')
    print(f.write('我存在了!!!'))
    sum = 1+'1'
    f.close()
#except OSError as reason:
#    print('文件出错\n错误的原因是: '+str(reason))
#except TypeError as reason:
#    print('类型出错\n错误的原因是: '+str(reason))
#except TypeError as reason:
#    print('类型出错\n错误的原因是: '+str(reason))
except (OSError,TypeError):
    print('出错了')
finally:
    f.close()
########################################################################
try:
    int('12')
except ValueError as reason:
    print('出错了' + str(reason))
else:
    print('没有异常')
########################################################################   
try:
    #f = open('date.txt','w')
    with open('date.txt','w') as f:
        # 自动关闭 不用else
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错了' + str(reason))

    
 

finally

无论如何都会执行
在这里插入图片描述

发布了35 篇原创文章 · 获赞 2 · 访问量 911

猜你喜欢

转载自blog.csdn.net/hk2121/article/details/104064589