zoukankan      html  css  js  c++  java
  • python 教程 第十一章、 异常

    第十一章、 异常
    1)    try/except/else格式

    try:
    
        s = raw_input('--> ')
    
    except EOFError:
    
        print 'Why did you do an EOF on me?'
    
    except:
    
        print 'Error occurred.'
    
    else:
    
    print 'Done' 

    except参数说明:
    except:             Catch all (or all other) exception types.
    except name:         Catch a specific exception only.
    except name as value:     Catch the listed exception and its instance.
    except (name1, name2):     Catch any of the listed exceptions.
    except (name1, name2) as value:  Catch any listed exception and its instance.
    else:             Run if no exceptions are raised.
    finally:             Always perform this block.

    2)    try/finally格式

    try:  
    
        fd=open("have-exists-file", "r")  
    
    finally:  
    
    fd.close() 

    3)    try/except/else/finally通用格式

    try:                        
    
        main-action
    
    except Exception1:
    
        handler1
    
    except Exception2:
    
        handler2
    
    ...
    
    else:
    
        else-block
    
    finally:
    
        finally-block 

    4)    assert语句
    用来声明某个条件是真的,并且在它非真的时候引发一个错误
    assert len('abc') < 1

    5)    raise引发异常

    class ShortInputException(Exception):
    
        def __init__(self, length):
    
            Exception.__init__(self)
    
            self.length = length
    
    try:
    
        s = raw_input('Enter something --> ')
    
        if len(s) < 3:
    
            raise ShortInputException(len(s))
    
    except ShortInputException, x:
    
        print 'Exception: length %d ' % (x.length)
    
    else:
    
    print 'No exception.' 
  • 相关阅读:
    APUE.3源码编译(Ubuntu16.04)
    《UNIX环境高级编程》(第三版)阅读笔记---2018-5-9
    css回归之用户界面
    css回归之文本
    js回归之字符串
    js回归之BOM
    js回归之事件
    百度前端面试总结
    书单
    剑指offer做题收获之一:补码
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6468838.html
Copyright © 2011-2022 走看看