(1)遇见 ZeroDivisionError 异常
print(5/0)
Traceback:
Traceback (most recent call last):
File "d:/vscode/hello.py", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
(2)使用 try-except 代码块
处理 ZeroDivisionError 异常的 try-except 代码块:
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
输出:
You can't divide by zero!
(3)使用 try-except-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)
输出:
First number: 4
Second number: 2
2.0
First number: 4
Second number: 0
You can't divide by 0!
First number: q
(4)处理 FileNotFoundError 异常
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
Traceback
Traceback (most recent call last):
File "d:/vscode/hello.py", line 2, in <module>
with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
将 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)
输出:
Sorry, the file alice.txt does not exist.
(5)发生异常时一声不吭(pass)
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = [
'alice.txt',
'siddhartha.txt',
'moby_dick.txt',
]
for filename in filenames:
count_words(filename)
输出:
PS D:\vscode> & C:/Users/Administrator/AppData/Local/Programs/Python/Python37/python.exe d:/vscode/hello.py
PS D:\vscode>
可以看出,except中使用pass后,什么也不执行了。
(6)存储数据 json.dump()和 json.load()
首先编写存储一组数字的程序,再编写将这些数字读取到内存中的程序。
第一个程序使用json.dump()存储数字
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
输出:numbers.json
[2, 3, 5, 7, 11, 13]
第二个程序使用json.load()读取数字
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
输出:
[2, 3, 5, 7, 11, 13]