Python 3 处理错误 TypeError:不允许捕获不从 BaseException 继承的类 [英] Python 3 handling error TypeError: catching classes that do not inherit from BaseException is not allowed

查看:173
本文介绍了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 方法时不显示 和这个 无法捕获模拟异常,因为它不继承 BaseException 还阅读了这个 https://medium.com/python-pandemonium/a-very-picky-except-in-python-d9b994bdf7f0

I read this tread Exception TypeError warning sometimes shown, sometimes not when using throw method of generator and this one Can't catch mocked exception because it doesn't inherit BaseException also read this https://medium.com/python-pandemonium/a-very-picky-except-in-python-d9b994bdf7f0

我用这段代码修复了它:

I kind of fix it with this code:

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

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

The result it's that ignores the error and go to the next while but I want to catch the error and print it.

推荐答案

我发布了问题 在西班牙堆栈中具有更好的结果.翻译和总结:发生该错误是因为在异常子句中您必须指明您捕获的是哪个异常.异常是从基类 Exception 继承(直接或间接)的类.

I post the question in Spanish Stack with better results. To translate and sum up: The error occurs because in the exception clause you must indicate which exception you capture. An exception is a class that inherits (directly or indirectly) from the base class Exception.

相反,我将 client.get_order 放在 python 期望异常名称的位置,而您放置的是对象的方法,而不是从 Exception 继承的类.

Instead I have put client.get_order where python expected the name of the exception, and what you have put is a method of an object, and not a class that inherits from 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 3 处理错误 TypeError:不允许捕获不从 BaseException 继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆