一、异常类型
(1)文件不存在:FileNotFoundError
(2)断言语句失败:AssertionError,当assert关键字后面的条件为假时,程序就会抛出AssertionError,assert语句一般是在测试程序的时候用于在代码程序中置入检查点
my_list=["xiaoxiaohui"]
assert len(my_list)>0
my_list.pop()
assert len(my_list)>0
AssertionError Traceback (most recent call last)
in ()
2 assert len(my_list)>0
3 my_list.pop()
----> 4 assert len(my_list)>0
AssertionError:
(3)尝试访问未知的对象属性:AttributeError:对象属性不存在的时候
my_list=['小小慧程序员']
my_list.fail()
AttributeError Traceback (most recent call last)
in ()
1 my_list=[‘小小慧程序员’]
----> 2 my_list.fail()
AttributeError: ‘list’ object has no attribute ‘fail’
(4)索引超出序列范围:IndexError
my_list=[1,2,3]
my_list[3]
IndexError Traceback (most recent call last)
in ()
1 my_list=[1,2,3]
----> 2 my_list[3]
IndexError: list index out of range
(5)在字典中查找一个不存在的关键字:KeyError
my_dict={"one":1,"two":2,"three":3}
my_dict["one"]
my_dict["four"]
KeyError Traceback (most recent call last)
in ()
1 my_dict={“one”:1,“two”:2,“three”:3}
2 my_dict[“one”]
----> 3 my_dict[“four”]
KeyError: ‘four’
(6)尝试访问一个不存在的变量:NameError
my
NameError Traceback (most recent call last)
in ()
----> 1 my
NameError: name ‘my’ is not defined
(7)操作系统的异常OSError,上面打开一个不存在的文件,FileNotFoundError,属于操作系统异常的子类
(8)python语法错误:SyntaxError
print " i love you !"
File “”, line 1
print " i love you !"
^
SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(" i love you !")?
(9)不同类型间的无效操作 TypeError
1+"1"
TypeError Traceback (most recent call last)
in ()
----> 1 1+“1”
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
(10)除数为0:ZeroDivisionError
5/0
ZeroDivisionError Traceback (most recent call last)
in ()
----> 1 5/0
ZeroDivisionError: division by zero
二、异常处理机制
程序发生异常,python会停止运行,并抛出第一个traceback,
使用try—except代码块来处理异常代码,即便出现异常,程序也可也正常运行,而不是返回让人疑惑的traceback
使用方法:当你认为可能发生错误时,将错误的部分放入try后面,except后面跟着发生错误时你希望如何处理的语句
1.处理 ZeroDivisionError错误
try:
print(5/0)
except ZeroDivisionError :
print("you can not divide by zero !")
you can not divide by zero !
以上,将有错误的代码放入try中,如果try运行起来没有问题,将跳过except 执行后面语句,有问题,则执行except后面的语句,用户看到了一条友好的信息,而不是traceback
使用异常可以避免程序崩溃,尝试traceback,trackback中有一些信息不希望用户看到,使用except 是一种很好的选择,
print("please input two numbers,and i will divide them.")
print("please enter 'q' to end!")
while True:
first_num=input("first number: ")
if first_num=='q':
break
second_num=input("second number: ")
if second_num=='q':
break
answer=int(first_num)/int(second_num)
print(answer)
please input two numbers,and i will divide them.
please enter ‘q’ to end!
first number: 5
second number: 4
1.25
first number: 5
second number: 0
ZeroDivisionError Traceback (most recent call last)
in ()
8 if second_num==‘q’:
9 break
—> 10 answer=int(first_num)/int(second_num)
11 print(answer)
ZeroDivisionError: division by zero
没有异常处理机制,程序崩溃
print("please input two numbers,and i will divide them.")
print("please enter 'q' to end!")
while True:
first_num=input("first number: ")
if first_num=='q':
break
second_num=input("second number: ")
if second_num=='q':
break
try:
answer=int(first_num)/int(second_num)
except ZeroDivisionError :
print("you can not divide by zero !")
else:
print(answer)
please input two numbers,and i will divide them.
please enter ‘q’ to end!
first number: 4
second number: 3
1.3333333333333333
first number: 4
second number: 0
you can not divide by zero !
first number:
以上,将可能出现错误的代码放在try后,如果有错,执行except,返回一条友好的语句“you can not divide by zero !”,程序继续运行,不会崩溃。依赖于try成功后需要执行的放入else后面执行
2.处理FileNotFoundError
filename="alice.txt"
with open(filename) as f_obj:
contents=f_obj.read()
FileNotFoundError Traceback (most recent call last)
in ()
1 filename=“alice.txt”
----> 2 with open(filename) as f_obj:
3 contents=f_obj.read()
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:
m="the file "+filename+" dose no exit !"
print(m)
the file alice.txt dose no exit !
基于此,我们还可以同时处理多个文件
filenames=["alice.txt",r"C:\Users\zhangfayu\Desktop\nihao.txt"]
for filename in filenames:
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
m="the file "+filename+" dose no exit !"
print(m)
else:
print(contents)
the file alice.txt dose no exit !
你好,与股份有个下HSAVCJH玉\nsqcugwg h vYQGCY\N \n fbwb wef 2`gaugvy 2gvgcgzGKGCblaI喊我vcYYYhlvb挨次\n\n\n\n\n]n\m\n\n\n\n\n\n\n\naHDTcQ w dgy gyGchvcgvuvSCVgiavcgvcOUCyovvxzvcZKHcyCHVKcvGVKZZZ
cUHCv
ACYGC
Ci b
ZJKCBW
hello
hi
可以看出,第一个文件不存在,抛出友好提示“the file alice.txt dose no exit !”,这不影响第二个文件的正常打开
3.失败时一声不吭:
filenames=["alice.txt",r"C:\Users\zhangfayu\Desktop\nihao.txt"]
for filename in filenames:
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
pass
else:
print(contents)
利用pass关键字,这样只会打开第二个文件,对于第一个文件的,不会输出traceback,也没有输出
pass还充当了占位符,可以便于以后的操作。
所以,在python中异常处理机制,trt-except-else,可以选择决定报告那些错误,用户只想看到结果,不想看到分析那些文件,就不需要将文件不存在的信息给他们,用pass即。python的错误处理结构让你能够细致的控制与用户分享错误信息的程度,要分享多少信息由你决定。