python - Python 3 处理错误 TypeError:不允许捕获不继承自 BaseException 的类
问题描述
当我运行此代码时:
i=0
while i<5:
i=i+1;
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except client.get_order as e:
print ("This is an error message!{}".format(i))
#End while
我收到了这个错误:
TypeError: catching classes that do not inherit from BaseException is not allowed
我读到这个异常类型错误警告有时会显示,有时在使用生成器的 throw 方法时不会显示,而这个Can't catch mocked exception 因为它不继承 BaseException也读过这个https://medium.com/python-pandemonium/a -非常挑剔的python-d9b994bdf7f0除外
我用这段代码修复它:
i=0
while i<5:
i=i+1;
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except:
print ("This is an error message!{}".format(i))
#End while
结果是忽略错误并转到下一个,但我想捕获错误并打印它。
解决方案
我在西班牙语堆栈中发布了这个问题,结果更好。翻译和总结:错误发生是因为在异常子句中您必须指出您捕获的异常。异常是(直接或间接)从基类 Exception 继承的类。
相反,我将 client.get_order 放在 python 期望异常名称的位置,而您放置的是对象的方法,而不是从 Exception 继承的类。
解决方案是这样的
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except Exception as e:
if e.code==-2013:
print ("Order does not exist.");
elif e.code==-2014:
print ("API-key format invalid.");
#End If
您需要为此处的每个异常编写代码
推荐阅读
- python - 从两个类继承(或)
- ios - 更新到 Xcode 12:无法将“DataRequest”类型的值转换为闭包结果类型“Void”
- css - 实现 Slick Slider 时使用混合模式中断的元素
- symfony - Api平台,部分数据相同时禁止POST方法
- javascript - 卡在 React-Native 推送通知中
- abap - 基于结构的 F4 搜索帮助。它是如何工作的?
- c# - 如何在不知道其名称的情况下删除索引?
- javascript - 在 JSON.stringify 之后发送和转换 Float32Array
- single-sign-on - 使用和不使用 SSO 通过 SCIM 进行用户配置
- python - Django 用户数据库实现