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.