每当发生让python不知所措的错误的时候,都会创建一个异常对象。如果编写了处理处理改异常的代码,程序将继续运行,如果未对异常处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
异常使用 try - except 代码块处理,执行指定操作的同时告诉python发生异常了怎么办?
1. 处理ZeroDivisionError异常
print(3/0)
被除数时不能为0的,但在python中为0了会怎么呢?
Traceback (most recent call last):
File "division.py", line 1, in <module>
print(3/0)
ZeroDivisionError: division by zero
python停止运行,并指出引发了哪种异常。发生异常也希望程序能继续运行怎么办呢?
2. 使用 try - except 代码块
当有可能发生错误时,可编写一个 try - except 代码块来处理可能引发的异常:
try:
print(3/0)
except ZeroDivisionError:
print("You can't divide by zero!")
运行结果:
You can't divide by zero!
3. 使用异常避免崩溃
发生错误时,如果程序还有工作没完成,妥善处理错误就尤为重要。
# 一个只执行除法运算的简单计算器
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)
如果用户给第二个数字输入0,就会出现:
Traceback (most recent call last):
File "division.py", line 12, in <module>
answer = int(first_number)/int(second_number)
ZeroDivisionError: division by zero
这样的信息会把不懂技术的用户搞糊;会对怀有恶意的用户暴露重要信息。
相关推荐:《Python视频教程》
4. 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: ")
if second_number == 'q':
break
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
运行结果:
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 3
Second number: 0
You can't divide by zero!
First number: 4
Second number: 2
2.0
First number: q
尝试执行 try 代码块中的代码:若引发了异常,执行except代码块的代码;若没有发生异常,执行else代码块。
5. 处理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'
上述代码运行错误是函数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)
运行结果:
Sorry, the file alice.txt does not exist.
告知用户文件不存在。
6. 分析文本
分析包含整本书的文本文件: 在网站http://www.gutenberg.org/下载文学文本The Lay of the Nibelung Men.txt,提取文本,并尝试计算包含了多少个单词:
filename = 'The-Lay-of-the-Nibelung-Men.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.")
运行结果:
The file The-Lay-of-the-Nibelung-Men.txt has about 124918 words.
7. 使用多个文件
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.")
定义一个可以计算文件有多少单词的函数,之后就可调用该函数来计算多个文件的:
filenames = ['A-Case-of-Sunburn.txt', 'moby_dick.txt', 'The-Lay-of-the-Nibelung-Men.txt']
for filename in filenames:
count_words(filename)
运行结果:
The file A-Case-of-Sunburn.txt has about 9416 words.
Sorry, the file moby_dick.txt does not exist.
The file The-Lay-of-the-Nibelung-Men.txt has about 124918 words.
8. 失败时一声不吭
若希望在不捕获到异常时一声不吭,继续执行:
try:
...
except FileNotFoundError:
pass
else:
...
在捕获到异常时,执行pass语句。