异常处理

2018-03-19  本文已影响0人  钟速
断言

assert 条件:条件为假时弹出异常AssertionError

try-except
try:
    检测范围
except Exception[ as reason]:
    出现异常(Exception)后的处理代码

例:

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错,原因是:' + str(reason))
try-finally

如果try中没有错误,则跳过except执行finally;如果try中有错误,则先执行except再执行finally。

try:
    f = open('test.txt')
    print(f.read())
    sum = 1 + '1'
except:
    print('出错了')
finally:
    f.close()
raise()

抛出一个异常
raise ZeroDivisionError
raise ZeroDivisionError('除数不能为0')

with

with会自动关闭文件

try:
    with open('data.txt', 'w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('文件出错,原因是:' + str(reason))
上一篇下一篇

猜你喜欢

热点阅读