Python 3 handling error TypeError: catching classes that do not inherit from BaseException is not allowed

Python 3 handling error TypeError: catching classes that do not inherit from BaseException is not allowed

当我运行这段代码时:

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

我读了这篇文章Exception TypeError warning sometimes shown, sometimes not when using throw method of generator and this one also read this https://medium.com/python-pandemonium/a-very-picky-except-in-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

结果是忽略错误并转到下一个,但我想捕获错误并打印出来。

我 post 西班牙语堆栈中的 question 有更好的结果。 翻译总结一下: 发生错误是因为在异常子句中你必须指明你捕获的是哪个异常。异常是 class 继承(直接或间接)自基础 class 异常。

相反,我把 client.get_order 放在了 python 期望异常名称的地方,你放的是对象的方法,而不是继承自的 class异常。

解决方法是这样的

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

您需要为 here

中的每个异常编写代码