#coding:gbk#division.py#print(5/0)#Output:#Traceback (most recent call last):# File "10.3.1处理ZeroDivisionError异常.py.py", line 4, in <module># print(5/0)#ZeroDivisionError: division by zero#上述错误ZeroDivisonError是一个一场对象#10.3.2使用try-except代码块try:print(5/0)except ZeroDivisionError:print("You can't divide by zero!")#10.3.3使用异常避免崩溃#division.pyprint("Give me two numbers, and I will divide them.")print("Enter 'q' to quit.")whileTrue:
first_number =input("\nFirst number: ")if first_number =='q':break
second_number =input("Second number: ")if second_number =='q':break
answer =int(first_number)/int(second_number)print(answer)#这个程序没有采取任何处理错误的措施,因此让它执行除数为0时,它将崩溃;#程序崩溃会使不懂技术的用户被搞糊涂,而且如果用户怀有恶意,他会通过traceback获悉你不希望他指定的信息。#例如,他知道你的程序文件名称,还将看到部分不能正常运行的代码。#有时候,训练有素的攻击者可根据这些信息判断出可对你的代码发起什么样的攻击。#10.3.4else代码块#通过将可能引发错误的代码放在代码块中,可提高这个程序抵御错误的能力print("Give me two numbers, and I will divide them.")print("Enter 'q' to quit.")whileTrue:
first_number =input("\nFirst number: ")if first_number =='q':break
second_number =input("Second number: ")try:
answer =int(first_number)/int(second_number)except ZeroDivisionError:print("You can't divide by 0!")else:print(answer)#依赖于try代码块成功执行的代码都应该放到else代码块中#try-except-else代码块的工作原理大致如下:# Python尝试执行try代码块中的代码;只有可能引发异常的代码才需要放在try语句中。# 有时候,有一些尽在try代码块成功执行时才需要运行的代码:这些代码应放在else代码块中。# else代码块告诉python,如果它尝试运行try代码块中的代码时发生了指定的异常,该怎么办。#通过预测可能发生错误的代码,可编写健壮的程序,它们即便面临无效数据或缺少资源,也能继续运行,从而能够抵御无意的用户错误和恶意的攻击。#10.3.5处理FileNotFoundError异常
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+ filename +" does not exist."print(msg)#10.3.6分析文本
title ="Alice in wonderland"print(title.split())
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+ filename +" does not exist."else:#计算文件大概包含多少单词
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+" words.")#10.3.7使用多个文件#word_count.pydefcount_words(filename):"""计算一个文件大致包含多少单词"""try:withopen(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)
filenames =['alice.txt','little_women.txt','siddhartha']for filename in filenames:
count_words(filename)#10.3.8失败时一声不吭defcount_words_1(filename):"""计算一个文件大致包含多少单词"""try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:pass#Python的pass语句可在代码块使用它来让Python什么都不做else:
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+" words.")
filenames =['alice.txt','little_women.txt','siddhartha']for filename in filenames:
count_words_1(filename)#pass语句还充当了占位符,它提醒你在程序的某个地方什么都没有做,并且以后也许要在这里做些什么,例如我们可能决定将这个程序中找不到的文件的名称写入到文件missing_files.txt中。#10.3.9决定报告哪些错误#略