1

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)

6
  • 5
    Trying to divide strings and ints should raise a TypeError. Try except (ValueError, TypeError): to catch that as well. Commented Jun 28, 2018 at 15:38
  • @PatrickHaugh, thank you for the response. This was just an example, is there a way to catch all possible error types. Provided methods are very big and complicated, and I am not sure what type of errors, they would throw. Commented Jun 28, 2018 at 15:43
  • 1
    Why not just except: without giving is a specific error (or list of errors) to handle? Commented Jun 28, 2018 at 15:48
  • Also, perhaps continue would be better than break if you don't want to end execution on the inner list. Commented Jun 28, 2018 at 15:55
  • python is giving a warning message saying (except is too broad which is not accepted by the rules of the company) .. and i would like the inner loop to end ( this was just an example, in our code, if inner fails, we have to move to the next item on the outer loop Commented Jun 28, 2018 at 15:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 one for not recommending to silently ignore all exceptions. This can make it very hard to find bugs that throw exceptions that are never seen. At least log them somewhere, including the traceback, before the break. logging.exception() can be helpful here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.