一、什么是异常
异常就是程序运行时发生错误的信号,在python中,错误触发的异常如下
二、什么时候最容易出异常
当你要处理的内容不确定的时候
有用户参与
有外界数据接入 : 从文件中读 从网络上获取
三、python中的异常种类



四、什么是异常处理
python解释器检测到错误,触发异常(也允许程序员自己触发异常)
程序员编写特定的代码,专门用来捕捉这个异常(这段代码与程序逻辑无关,与异常处理有关)
如果捕捉成功则进入另外一个处理分支,执行你为其定制的逻辑,使程序不会崩溃,这就是异常处理
五、为什么要进行异常处理
python解析器去执行程序,检测到了一个错误时,触发异常,异常触发后且没被处理的情况下,程序就在当前异常处终止,后面的代码不会运行,谁会去用一个运行着突然就崩溃的软件。
所以你必须提供一种异常处理机制来增强你程序的健壮性与容错性
六、如何进行异常处理

l = ['login','register'] for num,i in enumerate(l,1): print(num,i) try: num = int(input('num >>>')) print(l[num - 1]) except ValueError : # except处理的异常必须和实际报错的异常是相同的 print('请输入一个数字') print(l[num - 1])

l = ['login','register'] for num,i in enumerate(l,1): print(num,i) try: num = int(input('num >>>')) print(l[num - 1]) except ValueError : # 从上向下报错的代码只要找到一个和报错类型相符的分支就执行这个分支中的代码,然后直接退出分支 print('请输入一个数字') except IndexError : # 如果找不到能处理和报错类型相同的分支,会一直往下走,最后还是没有找到就会报错 print('只能输入1或2')

l = ['login','register'] for num,i in enumerate(l,1): print(num,i) try: num = int(input('num >>>')) print(l[num - 1]) except (ValueError,IndexError) : print('您输入的内容不合法')

def main(): l = [('购物',buy),('退货',back),('查看订单',show)] while True: for num,i in enumerate(l,1): print(num,i[0]) num = int(input('num >>>')) print(l[num - 1]) try: func = l[num - 1][1] func() except Exception: print('用户在选择了%s操作之后发生了不可知的异常' % l[num - 1][0]) main()

try: print('aaa') # 给某某某发邮件 # name # [][1] # 1/0 except NameError: # 网络不稳定,邮箱地址错误 print('name error') except IndexError: print('index error') except Exception as e: print('Exception') else: # 当try中的代码不发生异常的时候 走else分支 如果发送成功了 进行一些处理 print('else')

try: print('aaa') # 给某某某发邮件 name # [][1] # 1/0 except NameError: # 网络不稳定,邮箱地址错误 print('name error') except IndexError: print('index error') except Exception as e: print('Exception') else: # 当try中的代码不发生异常的时候 走else分支 如果发送成功了 进行一些处理 print('else') finally: # 无论如何都会被执行 print('finally')
七、异常处理的几种情况
try ... except
try ... except ... else
try ... finally
try ... except ... finally
try ... except ... else ... finally
八、自定义异常
import os class ExistsError(Exception): pass class KeyInvalidError(Exception): pass def new_func(path,prev): """ 去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。 1000,成功 1001,文件不存在 1002,关键字为空 1003,未知错误 ... :return: """ response = {'code':1000,'data':None} try: if not os.path.exists(path): raise ExistsError() if not prev: raise KeyInvalidError() pass except ExistsError as e: response['code'] = 1001 response['data'] = '文件不存在' except KeyInvalidError as e: response['code'] = 1002 response['data'] = '关键字为空' except Exception as e: response['code'] = 1003 response['data'] = '未知错误' return response
def func(path,prev): """ 去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。 1000,成功 1001,文件不存在 1002,关键字为空 1003,未知错误 ... :return: """ response = {'code':1000,'data':None} try: if not os.path.exists(path): response['code'] = 1001 response['data'] = '文件不存在' return response if not prev: response['code'] = 1002 response['data'] = '关键字为空' return response pass except Exception as e: response['code'] = 1003 response['data'] = '未知错误' return response
class MyException(Exception): def __init__(self,code,msg): self.code = code self.msg = msg pass try: raise MyException(1000,'操作异常') except MyException as obj: print(obj.code,obj.msg) print(obj) #(1000, '操作异常')
九、断言
assert 1==2 # 只能接受一个布尔值 False assert 1==1 # 只能接受一个布尔值 False print(123456) if 1 == int(input()): pass else: raise AssertionError