xinggevip

Python(8-1)异常处理
异常类型总结:https://fishc.com.cn/forum.php?mod=viewthread&tid=...
扫描右侧二维码阅读全文
02
2018/12

Python(8-1)异常处理

异常类型总结:
https://fishc.com.cn/forum.php?mod=viewthread&tid=45814&extra=page%3D1%26filter%3Dtypeid%26typeid%3D403

异常处理语句

try:
    sum = 1 + '1'
    f = open('文件.txt')
    print(f.read())
    f.close()
except (OSError,TypeError):
    print('找不到该文件')
>>> 找不到该文件

输出错误原因

try:
    sum = 1 + '1'
    f = open('文件.txt')
    print(f.read())
    f.close()
except OSError as ff:
    print('找不到该文件' + str(ff))
except TypeError as fff:
    print('类型错误' + str(fff))
>>> 类型错误unsupported operand type(s) for +: 'int' and 'str'

try finally语句处理异常

try:
    
    f = open('文件.txt','w')
    print(f.write('我是文本内容'))
    sum = 1 + '1'
except (OSError,TypeError):
    print('出错了T_T')
finally:
    f.close()
>>> 6
   出错了T_T

try else语句处理异常

try:
    print(int('123'))
except ValueError as reson:
    print('出错了:' + str(reson))
else:
    print('没有任何错误')
>>> 123
   没有任何错误

try with语句处理异常
自动关联打开的文件,处理异常后自动执行close语句关闭文件

try:
    with open('data.txt','w') as f:
        f.write('写入内容')
        for each_line in f:
            print(each_lin)
except OSError as reason:
    print('出错了:' + str(reason))
>>> 出错了:not readable
Last modification:December 2nd, 2018 at 02:16 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment