异常 管理程序执行期间发生错误的特殊对象 每当Python发生不知所措的错误时就创建一个异常对象 若编写处理该异常的代码,则程序继续进行,否则程序停止并显示traceback(包含有关异常的报告) 异常使用try-except代码块处理 它会让Python执行特定操作,并告诉发生异常之后的处理办法 使用代码块后发生异常也会继续运行,显示你编写的友好错误消息,而不是traceback。 ZeroDivisionError错误 除以0的错误 FileNotFoundError错误 文件不存在的错误 else代码块 包含依赖于try代码块成功执行的代码 pass会使Python什么都不做 例: word_count.py def count_words(filename): “”“计算一个文件大致包含多少个单词”"" ① try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = “Sorry, the file " + filename + " does not exist.” print(msg) else: # 计算文件大致包含多少个单词 words = contents.split() num_words = len(words) print(“The file " + filename + " has about " + str(num_words) +” words.") filename = ‘alice.txt’ count_words(filename) 注:如果将 msg = “Sorry, the file " + filename + " does not exist.” print(msg)换为pass,则输出内容不显示是否有不存在的文件。