1、python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让python不知所措的错误时,它都会创建一个异常对象。如果编写了处理该异常的代码,程序将继续运行,如果未对异常进行处理,程序将终止,并显示一个traceback,其中包含有关异常的报告。
2、使用try-except代码块
如果认为可能发生了错误时,可编写一个try-except代码块来处理可能引发的异常。如果try代码块中的代码运行起来没有问题,python将跳过except代码块;如果try代码块中的代码导致了错误,python将查找这样的except代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero")
输出为:
D:\www>python hello.py
You can't divide by zero
3、使用异常避免崩溃——else代码块
依赖于try代码块成功执行的代码都应放在else代码块中
while True:
first_number=input("First 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 0")
else:
print(answer)
输出为:
D:\www>python hello.py
First number:1
Second number:2
0.5
First number:1
Second number:0
You can't divide by 0
try-except-else代码块的工作原理:
python尝试执行try代码块中的代码,只有可能引发异常的代码才需要放在try语句中。有时候,有一些仅在try代码块成功执行时才能运行的代码;这些代码应该放在else代码块中。except代码块在尝试执行try代码块时的代码发生了指定异常时执行。
4、处理FileNotFoundError异常
filename='alice.txt'
try:
with open(filename) as file_object:
context=file_object.read()
except FileNotFoundError:
msg="sorry,the file "+filename+" does not exist."
print(msg)
else:
print(context)
输出为:
D:\www>python hello.py
sorry,the file alice.txt does not exist.
D:\www>python hello.py
I am alice.
5、分析文本
filename='alice.txt'
try:
with open(filename) as file_object:
context=file_object.read()
except FileNotFoundError:
msg="sorry,the file "+filename+" does not exist."
print(msg)
else:
words=context.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
输出为:
D:\www>python hello.py
The file alice.txt has about 3 words.
6、失败时一声不吭
使用pass语句
def count_words(filename):
try:
with open(filename) as file_object:
context=file_object.read()
except FileNotFoundError:
pass
else:
words=context.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['alice.txt','hello.txt','data.txt']
for filename in filenames:
count_words(filename)
输出为:
D:\www>python hello.py
The file alice.txt has about 3 words.
The file data.txt has about 7 words.