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
First you will want to extend an error. In this example, i am extending a
TypeError
:Then, to use it:
This will use a
try
–except
statement to check whether the variablestring
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.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:
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:
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 likeitem = data['keyofthethingyouwant']
oritem = data.get('keyofthethingyouwant')
then get items out ofitem
and check errors then.Use
https://docs.python.org/2/tutorial/errors.html