跳到正文

【Python学习】对异常的处理机制

1.异常的抛出 # encoding=UTF-8 class ShortInputException(Exception): '''一个由用户定义的异常类''' def __init__(self, length, atleast): # 让这个自定义的异常继承于Exception类 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, expected at least {1}') .format(ex.length, ex.atleast)) else: print('No exception was raised.') 2.异常的处理 try : text = input('Enter something -->') except EOFError: print('EOF error') except KeyboardInterrupt: print('KeyboardInterrupt error') else: print('You entered {}'.format(text))3.异常的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='') # 使得控制台中输出与的内容可以立马显示出来 sys.stdout.flush() print("Press ctrl+c now") # 为了确保它能运行一段时间 # time.sleep 函数任意在每打印一行后插入两秒休眠 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("(Cleaning up: Closed the file)")

评论

填写昵称与邮箱即可评论,无需登录。

推荐阅读