错误异常处理
python异常处理机制: try….except…finally…
如果异常则执行except后的语句,没有异常则直接跳过,
可以用else来提示没有异常 。
finally后的语句是必然执行的,不管try后的语句是否正确。
常见异常
异常 | 解释 |
---|---|
AttributeError | 试图访问一个对象没有的属性,比如foo.x,但是foo没有属性x |
IOError | 输入/输出异常;基本上是无法打开文件 |
ImportError | 无法引入模块或包;基本上是路径问题或名称错误 |
IndentationError | 语法错误(的子类) ;代码没有正确对齐 |
IndexError | 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] |
KeyError | 试图访问字典里不存在的键 |
KeyboardInterrupt | Ctrl+C被按下 |
NameError | 使用一个还未被赋予对象的变量 |
SyntaxError | Python语法错误 |
TypeError | 传入对象类型与要求的不符合 |
UnboundLocalError | 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它 |
ValueError | 传入一个调用者不期望的值,即使值的类型是正确的 |
// except: 捕获所有异常,except 异常名:捕获异常名对应的异常
try:
x = 5 / 0
f=open('我是一个不存在的文件')
f.read()
except ZeroDivisionError as e:
print("不能除0", e)
except OSError:
print('文件出错了')
except:
print('异常')
else:
print('没有异常')
finally:
f.close()
///自己创建异常raise
def method():
raise NotImplementedError('该方法未实现')
except 改变HTTP接口状态码
# -*- coding: utf-8 -*-
class ParamException(Exception):
def __init__(self, *args):
super().__init__(*args)
self.code = 451
class DataException(Exception):
def __init__(self, *args):
super().__init__(*args)
self.code = 452
class AlgException(Exception):
def __init__(self, *args, code=550):
super().__init__(*args)
self.code = code
class ModuleException(Exception):
def __init__(self, *args):
super().__init__(*args)
self.code = 540
# 541 算法模块更新异常
# 542: exception in loading model
# 543 算法模块卸载异常
# 544 算法模型加载异常
# 545 算法模型训练异常
# 546 算法模型评估异常
# 547 算法模型卸载异常
# 549 算法模型评估异常 SoftTimeLimitExceeded 算法模块超时(调用, 训练, 评估)
算法调用时,一旦捕获上面的异常,状态码就会变为上面的self.code。
如:
try:
1/0
except:
raise AlgException("不可以除0。", code=521)
postman返回结果:
{
“code”: 521,
“msg”: “不可以除0。”,
“result”: null
}