Exception

作者: Takkum | 来源:发表于2017-12-04 21:56 被阅读0次

    exceptions_handle.py

    # 异常的处理
    # try...except
    # 通常的语句在try块里  错误处理器放在except块里
    
    
    try:
        text = input('Enter something --> ')
    except EOFError:
        print('Why did you do an EOF on me?')
    except KeyboardInterrupt:
        print('You cancelled the operation.')
    else:
        print('You entered {}'.format(text))
        
    # 如果 except 后面不指定错误名称 那么就是处理所有错误
    # else 将在没有发生异常的时候执行
    

    exceptions_raise.py

    # 引发raise异常
    # 要提供错误名或异常名以及要抛出Thrown的对象
    
    class ShortInputException(Exception):
        '''一个由用户定义的异常类'''
        def __init__(self,length,atleast):
            Exception.__init__(self)
            self.length = length
            self.atleast = atleast
    
    try:
        text = input('Enter something --> ')
        if len(text) < 3:
            raise ShortInputException(len(text),3)
    except EOFError:
        print('Why did you do an EOF on me?')
    except ShortInputException as ex:
        print('ShortInputException: The input was ' + '{0} long, excepted at least {1}'.format(ex.length,ex.atleast))
    else:
        print('No exception was raised.')
    

    exceptions_finally.py

    # try ... finally
    # 主要是用在文件里面
    
    import sys
    import time
    
    f = None
    try:
        f = open('poem.txt')
        
        while True:
            line = f.readline()
            if len(line) == 0:
                break
            print(line,end='')
            # 以便print的内容可以被立即打印到屏幕上
            sys.stdout.flush()
            print('Press ctrl+c now')
            
            # 每打印一行后插入两秒休眠,让程序运行得比较缓慢
            time.sleep(2)
    except IOError:
        print('Could not find file poem.txt')
    except KeyboardInterrupt:
        print('!! You cancelled the reading from the file.')
    finally:
        if f:   # 这句话记得要
            f.close()
        print('(Clearning up:Closed the file)')
    

    exceptions_using_with.py

    # 在try块中获取资源(也就是open) 然后在finally块中释放资源(也就是close())
    # with语句可以很简单做到这一模式
    
    with open('opem.txt') as f:
        for line in f:
            print(line,end='')
    
    # 文件的关闭交由with ... open来完成
    # with 会获取open返回的对象f
    # 然后在代码块开始之前调用 f.__enter__函数 
    # 在代码块结束之后调用 f.__exit__函数
    

    相关文章

      网友评论

          本文标题:Exception

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