1. 处理ZeroDivisionError 异常

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

ZeroDivisionError 是一个异常对象。Python无法按你的要求做时,就会创建这种对象。在这种情况下,Python将停止运行程序,并指出引发了哪种异常,而我们可根据这些信息对程序进行修改。下面我们将告诉Python,发生这种错误时怎么办;这样,如果再次发生这样的错误,我们就有备无患了。

2.使用try-except 代码块

  1. try:
  2. print(5/0)
  3. except ZeroDivisionError:
  4. print("You can't divide by zero!")

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

  1. You can't divide by zero!

3.使用异常避免崩溃

  1. print("Give me two numbers, and I'll divide them.")
  2. print("Enter 'q' to quit.")
  3. while True:
  4. first_number = input("\nFirst number: ")
  5. if first_number == 'q':
  6. break
  7. second_number = input("Second number: ")
  8. if second_number == 'q':
  9. break
  10. answer = int(first_number) / int(second_number)
  11. print(answer)
  1. Give me two numbers, and I'll divide them.
  2. Enter 'q' to quit.
  3. First number: 5
  4. Second number: 0
  5. Traceback (most recent call last):
  6. File "division.py", line 9, in <module>
  7. answer = int(first_number) / int(second_number)
  8. ZeroDivisionError: division by zero

程序崩溃可不好,但让用户看到traceback也不是好主意。不懂技术的用户会被它们搞糊涂,而且如果用户怀有恶意,他会通过traceback获悉你不希望他知道的信息。例如,他将知 道你的程序文件的名称,还将看到部分不能正确运行的代码。有时候,训练有素的攻击者可根据这些信息判断出可对你的代码发起什么样的攻击。

4.else代码块

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

  1. print("Give me two numbers, and I'll divide them.")
  2. print("Enter 'q' to quit.")
  3. while True:
  4. first_number = input("\nFirst number: ")
  5. if first_number == 'q':
  6. break
  7. second_number = input("Second number: ")
  8. try:
  9. answer = int(first_number) / int(second_number)
  10. except ZeroDivisionError:
  11. print("You can't divide by 0!")
  12. else:
  13. print(answer)

我们让Python尝试执行try 代码块中的除法运算,这个代码块只包含可能导致错误的代码。依赖于try 代码块成功执行的代码都放在else 代码块中;在这个示例中,如 果除法运算成功,我们就使用else 代码块来打印结果。

  1. Give me two numbers, and I'll divide them.
  2. Enter 'q' to quit.
  3. First number: 5
  4. Second number: 0
  5. You can't divide by 0!
  6. First number: 5
  7. Second number: 2
  8. 2.5
  9. First number: q

5. 处理FileNotFoundError异常

  1. filename = 'alice.txt'
  2. with open(filename) as f_obj:
  3. contents = f_obj.read()

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

  1. Traceback (most recent call last):
  2. File "alice.py", line 3, in <module>
  3. with open(filename) as f_obj:
  4. FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
  1. filename = 'alice.txt'
  2. try:
  3. with open(filename) as f_obj:
  4. contents = f_obj.read()
  5. except FileNotFoundError:
  6. msg = "Sorry, the file " + filename + " does not exist."
  7. print(msg)
  1. Sorry, the file alice.txt does not exist.

6.分析文本

  1. >>> title = "Alice in Wonderland"
  2. >>> title.split()
  3. ['Alice', 'in', 'Wonderland']
  1. filename = 'alice.txt'
  2. try:
  3. with open(filename) as f_obj:
  4. contents = f_obj.read()
  5. except FileNotFoundError:
  6. msg = "Sorry, the file " + filename + " does not exist."
  7. print(msg)
  8. else:
  9. # 计算文件大致包含多少个单词
  10. words = contents.split()
  11. num_words = len(words)
  12. print("The file " + filename + " has about " + str(num_words) + " words.")
  1. The file alice.txt has about 29461 words.

7.使用多个文件

  1. def count_words(filename):
  2. """计算一个文件大致包含多少个单词"""
  3. try:
  4. with open(filename) as f_obj:
  5. contents = f_obj.read()
  6. except FileNotFoundError:
  7. msg = "Sorry, the file " + filename + " does not exist."
  8. print(msg)
  9. else:
  10. # 计算文件大致包含多少个单词
  11. words = contents.split()
  12. num_words = len(words)
  13. print("The file " + filename + " has about " + str(num_words) +
  14. " words.")
  15. filename = 'alice.txt'
  16. count_words(filename)
  1. def count_words(filename):
  2. --snip--
  3. filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
  4. for filename in filenames:
  5. count_words(filename)
  1. The file alice.txt has about 29461 words.
  2. Sorry, the file siddhartha.txt does not exist.
  3. The file moby_dick.txt has about 215136 words.
  4. The file little_women.txt has about 189079 words.

8.失败时一声不吭

  1. def count_words(filename):
  2. """计算一个文件大致包含多少个单词"""
  3. try:
  4. --snip-
  5. except FileNotFoundError:
  6. pass
  7. else:
  8. --snip-
  9. filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
  10. for filename in filenames:
  11. count_words(filename)
  1. The file alice.txt has about 29461 words.
  2. The file moby_dick.txt has about 215136 words.
  3. The file little_women.txt has about 189079 words.