什么是异常?
- 程序在运行过程中,发生了未知的事件,影响到了程序的正常运行
- 异常是一种事件
- 异常会影响到程序正常运行
第一个异常
运行程序:a = 10b = 0c = a/bprint(c)

出现了ZeroDivisionError异常
出现异常会造成程序停止异常捕获
使用try except捕获异常
代码:try:代码except:出现异常的代码
可以捕获异常的类型try:result = a / bprint('没有异常',result)except:# 如果代码有异常会执行 ,没有异常并不会执行print('出现了异常')
try:result = a/bprint('没有异常',result)except Exception as error:# 如果代码有异常会执行 ,没有异常并不会执行print('出现了异常',error)
finally
try语句中使用finally,finally中代码不论有没有出现异常都会执行
格式:
例如:try:逻辑代码finally:无论是否出现异常,都会执行
程序出现异常也会执行try:a = 1 / 0print("异常之后的代码", a)finally:print("finally里的代码")
finally中的代码try except finally语法
格式:
例如读写文件: ```python f = open(‘a.txt’,’w’)try:逻辑代码except Exception as error:print(error)finally:无论是否出现异常,都会执行
try: f.write(‘hello’)
# 出现异常a = 10b = 0re = a/b
except: print(‘出现异常’) finally: # 即使程序出现异常 finally里面的代码也可以继续执行
# 必须要关闭 内存泄漏f.close()print('文件已经关闭了')
无论文件是否操作失败,最终都需要关闭文件<br />所以把文件关闭的方法放到`finally`中<a name="ADNO6"></a>## try except else finally语法格式:```pythontry:逻辑代码except Exception as error:print(error)else:没有出现异常的逻辑finally:无论是否出现异常,都会执行
例如:
a = 10b = 0try:result = a / bprint(result)except:print('出异常')else:print('没有出异常')finally:print('最终执行的代码')
多重捕获
try:a = 1 / 0b = [1, 2]c = b[4]except IndexError as error:print("indexerror 错误逻辑")except ZeroDivisionError as error:print(error)
常见的异常类型
IndexError
数组下表越界异常
# 角标越界异常lst = [10, 20, 30]print(lst[6])
KeyError
字典中键不存在
# KeyError 字典中 的键不存在d = {'name':'张三','age':30}print(d['phone'])
ValueError
值类型错误
# ValueError 数据转换时出错str = 'abc'print(int(str))
AttributeError
对象中属性、函数不存在
class Person:def __init__(self):self.name = '张三'self.age = 30p = Person()print(p.id)

