skip to Main Content

I am querying the twitter api and loading the return values that i want into a variable

 gotdata = data.values()[1][10]['text']

However this line shows up in the logs when the app crashes
How can I make this assignment fail gracefully so that the app doesn’t crash when it fails?

3

Answers


  1. First you will want to extend an error. In this example, i am extending a TypeError:

    # NotIntError is raised if the item is not an integer
        class NotIntError(TypeError):
        msg=""
    
        # Constructor or Initializer
        def __init__(self,wrongInput):
            self.msg=str(wrongInput)+" is not an integer."
    
        # __str__ is to print the value
        def __str__(self):
            return self.msg
    

    Then, to use it:

    def encodeB32(self,string):
        try:
            if type(string)!=type(""):
                raise NotStringError(string)
    
            return base64.b32encode(string)
    
        except NotStringError as e:
            return self.name+" has issued a new error: "+str(e)
    

    This will use a tryexcept statement to check whether the variable string is a string or not before encoding it. Keep in mind, this is just an example, but you can easily modify it to fit your use.

    Login or Signup to reply.
  2. As Matias Cicero said, you are assuming too much about the data you get back from twitter (ie, using values for a dict), however the pythonic way to handle this is to try first and ask questions later, so really what you should do is handle the exception:

    gotdata = None
    try:
        gotdata = data.values()[1][10]['text']
    except Exception as e:
       # do something with your exception
       print(str(e))
    

    What is wrong with the above code is that it assumes some things, like that you will check to see if gotdata is not None when you go to use it, and that you dont care about what kind of Exception is raised.

    data might not have an attribute called values or data.values() might not have any items.

    to combat this uncertainty you can cascade the exception:

    gotdata = None
    try:
        gotdata = data.values()[1][10]['text']
    except IndexError:
        print("some IndexError occured")
    except Exception as e:
       # do something with your exception
       print(str(e))
    

    That way we can see whether the error was a IndexError or something else and act accordingly.

    The last thing is more of a usage problem, if you get a dictionary back from the api its usually good practice not to treat the dictionary like a list by using values() because the order of dictionaries is not guaranteed.

    You should check the key or value of the item to determine what to do with it.

    so rather than data.values()[1]... you should probably use something like item = data['keyofthethingyouwant'] or item = data.get('keyofthethingyouwant') then get items out of item and check errors then.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search