Exception

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 hierarchy¶ The class hierarchy for built-in exc...
    庞贝船长阅读 3,309评论 1 0
  • RuntimeException# You never need to write an exception sp...
    华山野老阅读 327评论 0 3
  • 异常是软件系统不可避免的的问题,软件系统在运行中难免发生不可预知的错误,为了避免异常造成软件自动停止运行造成损失,...
    田文健阅读 275评论 0 0
  • 更多 Java 基础知识方面的文章,请参见文集《Java 基础知识》 Java Exception Class D...
    专职跑龙套阅读 473评论 0 1
  • 还要在窗口看多少次日落 眼中才会出现你的背影 玻璃上勇敢的雨滴 一次又一次的相遇 却也只留下孤独的痕迹 我养了花 ...
    说书客阅读 239评论 0 0