task03异常打卡《Python基础》p45-p52

异常

处理ZeroDivisionEorror异常

>>>print(5/0)
Traceback (most recent call last):    
File "division.py", line 1, in <module>      				print(5/0) 
 ❶ ZeroDivisionError: division by zero

使用try-except代码块

try:    
print(5/0) 
except ZeroDivisionError:
    print("You can't divide by zero!")

我们将导致错误的代码行print(5/0) 放在了一个try 代码块中。如果try 代码块中的代码运行起来没有问题,Python将跳过except 代码块;如果try 代码块中的代码导致了 错误,Python将查找这样的except 代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。
在这个示例中,try 代码块中的代码引发了ZeroDivisionError 异常,因此Python指出了该如何解决问题的except 代码块,并运行其中的代码。这样,用户看到的是一条友 好的错误消息,而不是traceback:

You can't divide by zero!

如果try-except 代码块后面还有其他代码,程序将接着运行,因为已经告诉了Python如何处理这种错误。下面来看一个捕获错误后程序将继续运行的示例。

使用异常避免崩溃

发生错误时,如果程序还有工作没有完成,妥善地处理错误就尤其重要。这种情况经常会出现在要求用户提供输入的程序中;如果程序能够妥善地处理无效输入,就能再提示用 户提供有效输入,而不至于崩溃。
程序崩溃可不好,但让用户看到traceback也不是好主意。不懂技术的用户会被它们搞糊涂,而且如果用户怀有恶意,他会通过traceback获悉你不希望他知道的信息。例如,他将知 道你的程序文件的名称,还将看到部分不能正确运行的代码。有时候,训练有素的攻击者可根据这些信息判断出可对你的代码发起什么样的攻击。

print("Give me two numbers, and I'll divide them.")  print("Enter 'q' to quit.")  
while True:
 ❶     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)

结果

Give me two numbers, and I'll divide them. 
Enter 'q' to quit. 
First number: 5 
Second number: 0 
Traceback (most recent call last):  
	File "division.py", line 9, in <module>    
		answer = int(first_number) / int(second_number) ZeroDivisionError: division by zero

通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。错误是执行除法运算的代码行导致的,因此我们需要将它放到try-except 代码块 中。这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中:

print("Give me two numbers, and I'll divide them.")  print("Enter 'q' to quit.")  
while True:      
	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

结果

Give me two numbers, and I'll divide them. 
Enter 'q' to quit. 
First number: 5 
Second number: 0 
You can't divide by 0! 

First number: 5 
Second number: 2 
2.5 

First number: q

处理filenotfounderror

Python无法读取不存在的文件,因此它引发一个异常:

Traceback (most recent call last):  
File "alice.py", line 3, in <module>    
	with open(filename) as f_obj: 
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

在上述traceback中,最后一行报告了FileNotFoundError 异常,这是Python找不到要打开的文件时创建的异常。在这个示例中,这个错误是函数open() 导致的,因此要处理 这个错误,必须将try 语句放在包含open() 的代码行之前:

filename = 'alice.txt' 
try:
    with open(filename) as f_obj:
       contents = f_obj.read() 
 except FileNotFoundError:
     msg = "Sorry, the file " + filename + " does not exist."
     print(msg)

在这个示例中,try 代码块引发FileNotFoundError 异常,因此Python找出与该错误匹配的except 代码块,并运行其中的代码。最终的结果是显示一条友好的错误消息,而 不是traceback:

Sorry, the file alice.txt does not exist.

失败时一声不吭

在前一个示例中,我们告诉用户有一个文件找不到。但并非每次捕获到异常时都需要告诉用户,有时候你希望程序在发生异常时一声不吭,就像什么都没有发生一样继续运行。 要让程序在失败时一声不吭,可像通常那样编写try 代码块,但在except 代码块中明确地告诉Python什么都不要做。Python有一个pass 语句,可在代码块中使用它来让Python 什么都不要做:

  def count_words(filename):     
   		"""计算一个文件大致包含多少个单词"""      			
   		try:        
    	 --snip-      
     except FileNotFoundError:pass
	 else: 
          --snip-
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] 
 for filename in filenames:      		   
		count_words(filename)

相比于前一个程序,这个程序唯一不同的地方是❶处的pass 语句。现在,出现FileNotFoundError 异常时,将执行except 代码块中的代码,但什么都不会发生。这种错误 发生时,不会出现traceback,也没有任何输出。用户将看到存在的每个文件包含多少个单词,但没有任何迹象表明有一个文件未找到:

The file alice.txt has about 29461 words. The file moby_dick.txt has about 215136 words. 
The file little_women.txt has about 189079 words.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值