美文网首页
异常处理

异常处理

作者: 钟速 | 来源:发表于2018-03-19 20:56 被阅读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))
    

    相关文章

      网友评论

          本文标题:异常处理

          本文链接:https://www.haomeiwen.com/subject/jiveqftx.html