python的常见异常处理
异常: 在程序运行过程中影响程序正常运行的内容, 称为异常.
print(a)
NameError
li=[1,2,3,4]
print(li[4])
IndexError:索引错误
d=dict(a=1,b=2)
print(d['c'])
KeyError
print(10/(2-2))
ZeroDivisionError:除0错误
class Student(object):
def __init__(self,name,age):
self.name=name
self.age=age
def echo(self):
print(self.name,self.age)
s1=Student('westos',10)
print(s1.scores)
s1.echo()
AttributeError:对象没有该属性
with open('/tmp/passwd9') as f:
print(f.read(5))
FileNotFoundError:没有该文件
tey-except语句
try:
print(a)
如果出现NameError时,不报错,只显示except语句里面执行的内容.
except NameError:
print('name error')
print('hello')
print('hello1')
捕获异常
try:
f=open('hello.txt','w')
f.write('这是一个测试文件')
注意:except语句不一定会执行,只有在try语句中出现IOError报错时,才会执行
except IOError as e:
print(e)
print('没有找到文件或者文件读取失败')
如果没有捕获到异常,则执行else语句的内容
else:
print('文件内容写入成功')
无论是否捕获到异常,都执行的语句
finally:
f.close()
print('文件已经关闭')
不指定异常类型的except语句
try:
f=open('hello.txt')
f.write('这是一个测试文件')
f.read()
except:
print('捕获所有的异常')
else:
print('如果没有捕获到异常,执行else语句')
finally:
f.close()
print('有无异常都会执行')
捕获多个异常
抛出异常和触发异常
raise:关键字,用来抛出异常,抛出异常的名称,抛出异常的详细显示
def get_age(age):
if 0<age<=200:
print(age)
else:
raise Exception('invaild age')
get_age(100)
get_age(1000)
自定义异常类
所有的异常实际上是一个类,所以异常的父类都是BaseException
IOError,IndexError,KeyError,FileExistsError
class AgeError(BaseException):
pass
def get_age(age):
if 0<age<=200:
print(age)
else:
raise AgeError('invaild age')
get_age(1000)
get_age(100)
抛出异常与继承
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")