# 可以在except中处理异常,使下一次能正常运行try:
f =open('yang.txt',"r")print(f.read())
f.close()except FileNotFoundError:'可以在except处理异常,以免下次出现相同问题'print("FileNotFoundError!!!")
f =open('yang.txt',"w")
f.write('hello yang!')
f.close()
Exception捕获所有异常
try:
f =open('file.txt','r')
f.read()except Exception as e:print(e)# >[Errno 2] No such file or directory: 'file.txt'
else 和 finally
try:print(num)except:# 捕获到异常print("catch except")else:# 没有发生异常会执行print('''don't find except''')finally:# 始终会执行print('I must execute')
异常的传递
01.try嵌套
# 通过try嵌套有利于发现异常try:try:print(num)finally:print('内部finally')except Exception as e:print('catch inner except %s'% e)# >内部finally# catch inner except name 'num' is not defined
02.函数的嵌套调用
deffun1():print(num)deffunc2():
fun1()try:
func2()except Exception as e:print('catch inner function except %s'% e)# catch inner function except name 'num' is not defined# 还可以在func2()或者func1()中捕获# 在异常少的地方进行捕获,比较方便找到异常
抛出自定义异常
classAgeError(Exception):def__init__(self, age):
self.age = age
def__str__(self):return"{} AgeError age is illegal".format(self.age)classPerson(object):def__init__(self, name, age):if1< age <150:
self.name = name
self.age = age
else:raise AgeError(age)
xm = Person('yang',222)# raise AgeError(age)# __main__.AgeError: 222 AgeError age is illegal