Chuox
Chuox

Reputation: 793

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

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.

Upvotes: 29

Views: 144638

Answers (3)

pymen
pymen

Reputation: 6549

Another case when it may happen because the except clause in Python expects either a single exception class or a tuple of exception classes. Using a list directly is not valid syntax.

Wrong

try:
   something()
except [Exception1, Exception2] as e:
   process_exception(e)

Correct

try:
   something()
except (Exception1, Exception2) as e:
   process_exception(e)

Upvotes: 7

Esteban
Esteban

Reputation: 180

Check that you are importing the exception correctly. For example, if you are using sockets, except timeout won't work except you are importing the timeout exception:

from socket import timeout

Upvotes: 0

Chuox
Chuox

Reputation: 793

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

Upvotes: 32

Related Questions