How to handle Exception Handling in Python - python

If a list_goods[i] item does not exist in all_keys variable which is a keys of dictionary, I am supposed to catch an exception and adds the item followed by a value "none" to a new dictionary variable. However my codes does not work. Appreciate it if someone could point me in the right direction, Thanks!P.s I am not supposed to use If else in this assignment.
List and Dictionary in main method
dict_q2 = {"vinegar": [120.0, 100], "ketchup": [950, 1000],"apples": [850,1100],"oranges": [1050, 0]
}
list_q2 = ["ketchup","oranges","pear"]
Function to take in the above list and dict
def compute_unit_prices(dict_goods, list_goods):
#dict variable with name of good as key and unit prices as values.
return_dict = {}
all_keys = dict_goods.keys()
i =0
#Try block
try:
while (list_goods[i] in all_keys):
goods_name = list_goods[i]
storage = dict_goods[goods_name]
results = storage[0] / storage[1]
return_dict.update({goods_name:results})
i = i+1
except KeyError as e:
return_dict.update({goods_name:"none"})
# If zeroDivisionError is encountered, this block of code is used
except ZeroDivisionError as e:
results = -1
return_dict.update({goods_name:results})
# This block of code works if errors other than the above two occurs
except:
return_dict = {}
finally:
print(return_dict)

You was told to make sure that your code throws exceptions (run-time error) and catches them with try. And yet your code avoids iterating over the missing dictionary keys due to a peculiar while loop condition. Which is wrong on many levels. Better refactor to for i in range(len(list_goods)) loop. Otherwise while exits the loop on the first key out of the dictionary, so the KeyError exception does not have a single chance to occur. Also you risk i running out of the boundaries.
Move exception handling inside the loop. Otherwise the first exception will terminate the loop, and you want to process each and every element of the list.
Remove finally. You do not need it any more. Just print the result outside of the loop.
PS. Actually for good in list_goods is more pythonic, use that if you comfortable enough with python loop, but you will need to do more changes inside the loop.

Related

Continue the loop after an exception used in python

I am trying to run a loop with try and exception in python. Initially it runs for p=0 and j=1,2 then falls into the exception. the problem is that then I would like the loop to continue for p=1 and j=1,2,2....can you help me thanks! I tried something like this but it's not working
for p in range(1):
for j in range(23):
try:
b = response_json[0]['countries'][p]['names'][j]['values']
except:
break
Overall, using exceptions to handle normal flow is a bad pattern. Exceptions are for, well, exceptions.
Looks like you are trying to iterate over an array with missing keys. Instead of trying each key, you could iterate over the collection directly
country_data = response_json[0]['countries']
for country in country_data:
for name in country['names']:
b = name['values']
Replace break with continue (or pass).
break jumps to the end of the loop, continue jumps back to the start to continue with the next iteration. pass is a no-op used when a block is empty.

Python Error Handling On Called Methods

I would like to continue my loop if the called method throws an exception. This is a simple example,my actual code is pretty complicated and do not want to put error handling in all the called methods.
list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]
def parse(item):
item / 1
for list in list_of_lists:
for item in list:
try:
parse(item)
except ValueError:
break
This throws an exception, as soon as it hits the parse method. I was hoping that there is a way, that it just moves on to continue my loop. (outer loop)
In this case you are trying to divide a string by an int which raises a TypeError and not a ValueError, that's why your code throws an error.
If you want to catch all possible errors you can just do:
try:
parse(item)
except:
break
I wouldn't recommend it though, since in your case there seems to be a lot of complicated functions that can raise many different errors, it is probably better not to catch everything since you can miss an important error.
I would advise you to just run several times the code to find out all the possible errors and have a specific catch for every one, just to be sure there won't be an unrelated error you didn't anticipate

Python - inside except statement call continue OR raise based on if result

in a class I have method called "place(dictionary)" that check every object in dictionary and add it in a class variable if no exception were raised.
Based on a boolean variable called ignore_invalid I want to choose to continuing the loop with the next object in the dictionary simply avoiding to add the one that had raised an exception OR blocking the loop re-raising the exception.
The code is something like this:
class MyOwnException1()
[...]
class MyOwnException2()
[...]
[..my class definition..]
def place(self, elements, ignore_invalid=False):
for coordinates in elements:
try:
if method_checker1(coordinates):
raise MyOwnException1("...")
elif method_checker2(coordinates):
raise MyOwnException2("...")
else:
print "Current coordinates are valid. Adding them."
# adding the current coordinates
[..]
except (MyOwnException1, MyOwnException2) as my_exception:
print my_exception
if not ignore_invalid:
print "Stop the loop"
raise
else:
print "Continue the loop with next coordinates"
continue
This code is giving me error on the raise lines: seems I can't use the "raise" and "continue" in the same "except".
What is the best way to do that?
EDIT: my IDE had a bug in the output console; after an exception, also if ignore_invalid was true, it stopped to reproduce output.
Here a stupid and semplified example of what I did (that run correctly)
http://pastebin.com/FU2PVkhb
When you raise your exception in except block, then it will stop the loop. When you set ignore_invalid=True, then the loop will continue running.
That's what I understand based on what you asked. Anyway,you need to give your error traceback here.
While I can't reproduce the error you're getting, you can avoid this and make it much more readable if you avoid throwing the exceptions in the first place:
def place(self, elements, ignore_invalid=False):
for coordinates in elements:
if not ignore_invalid:
if method_checker1(coordinates):
raise MyOwnException1("...")
elif method_checker2(coordinates):
raise MyOwnException2("...")
print "Current coordinates are valid. Adding them."
# adding the current coordinates
#...
Of course, this is only functionally equivalent if your method_checkers are pure

Why use else in try/except construct in Python?

I am learning Python and have stumbled upon a concept I can't readily digest: the optional else block within the try construct.
According to the documentation:
The try ... except statement has an optional else clause, which, when
present, must follow all except clauses. It is useful for code that
must be executed if the try clause does not raise an exception.
What I am confused about is why have the code that must be executed if the try clause does not raise an exception within the try construct -- why not simply have it follow the try/except at the same indentation level? I think it would simplify the options for exception handling. Or another way to ask would be what the code that is in the else block would do that would not be done if it were simply following the try statement, independent of it. Maybe I am missing something, do enlighten me.
This question is somewhat similar to this one but I could not find there what I am looking for.
The else block is only executed if the code in the try doesn't raise an exception; if you put the code outside of the else block, it'd happen regardless of exceptions. Also, it happens before the finally, which is generally important.
This is generally useful when you have a brief setup or verification section that may error, followed by a block where you use the resources you set up in which you don't want to hide errors. You can't put the code in the try because errors may go to except clauses when you want them to propagate. You can't put it outside of the construct, because the resources definitely aren't available there, either because setup failed or because the finally tore everything down. Thus, you have an else block.
One use case can be to prevent users from defining a flag variable to check whether any exception was raised or not(as we do in for-else loop).
A simple example:
lis = range(100)
ind = 50
try:
lis[ind]
except:
pass
else:
#Run this statement only if the exception was not raised
print "The index was okay:",ind
ind = 101
try:
lis[ind]
except:
pass
print "The index was okay:",ind # this gets executes regardless of the exception
# This one is similar to the first example, but a `flag` variable
# is required to check whether the exception was raised or not.
ind = 10
try:
print lis[ind]
flag = True
except:
pass
if flag:
print "The index was okay:",ind
Output:
The index was okay: 50
The index was okay: 101
The index was okay: 10

syntaxError: 'continue' not properly in loop

I have been struggling with this error for a while now and there seems to be different opinions regarding why the interpreter complains about the 'continue'. So I would like to provide the erroneous code below.
import tweepy
import time
def writeHandlesToFile():
file = open("dataFile.txt","w")
try:
list = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
print "cursor executed"
for item in list:
file.write(item.screen_name+"\n")
except tweepy.error.TweepError as e:
print "In the except method"
print e
time.sleep(3600)
continue
The reason I am particular on including the continue at the end is because I would like for the program to restart execution at the top from where it left off after the sleep in order to preserve the program state. I need the sleep in order to abide by the twitter api rate limits wherein the api only allows you to make a certain number of requests every hour.
So anyone who might see my mistake naive or otherwise please do point it out or please provide me with an alternative implementation without the use of the continue statement.
BTW I do not have tabs and spaces mixed as was suggested in another post.
Thank you for your help in advance.
continue is only allowed within a for or while loop. You can easily restructure your function to loop until a valid request.
def writeHandlesToFile():
while True:
with open("dataFile.txt","w") as f:
try:
lst = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
print "cursor executed"
for item in lst:
f.write(item.screen_name+"\n")
break
except tweepy.error.TweepError as e:
print "In the except method"
print e
time.sleep(3600)
The problem might be in the way you are using continue
continue may only occur syntactically nested in a for or while loop,
but not nested in a function or class definition or finally statement
within that loop.6.1It continues with the next cycle of the nearest
enclosing loop.

Categories

Resources