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

Chuox picture Chuox · Nov 5, 2018 · Viewed 44.5k times · Source

When I run this code:

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

I got this error:

TypeError: catching classes that do not inherit from BaseException is not allowed

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.

Answer

Chuox picture Chuox · Nov 28, 2018

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.

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.

The solution goes this way

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

You'll need to code for every exception in here