Task06.异常处理

处理ZeroDivisionError异常

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!")
You can't divide by zero!

使用异常避免崩溃

 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)

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)  

处理FileNotFoundError 异常

filename = 'alice.txt'
with open(filename) as f_obj:  
   contents = f_obj.read()
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'
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)

分析文本

>>> title = "Alice in Wonderland" 
>>>> title.split()
> ['Alice', 'in', 'Wonderland']
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) 
  else:    
    # 计算文件大致包含多少个单词    
      words = contents.split() 
           num_words = len(words) 
                print("The file " + filename + " has about " + str(num_words) + " words.")

使用多个文件

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)
def count_words(filename): 
   --snip
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:  
  count_words(filename)
The file alice.txt has about 29461 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dick.txt has about 215136 words. 
The file little_women.txt has about 189079 words.

失败时一声不吭

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)
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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值