1

i'm stuck with my simple code, i'm a newbie for coding.. I'm using python and In my list i have bad values that made exceptions (httperror : 404) . I want to ignore this exceptions and continue my loop. But with my code, the print("Http error") loop again and again. I don't know how to pass this exception to loop the entire code again.

while i < len(list_siret):   
    try : 
        data = api.siret(list_sirets[i]).get()
        str_datajs = json.dumps(data, indent= 4)
        a_json = json.loads(str_datajs)
        i +=1
        print("test1", i ,str_datajs)    
    except urllib.error.URLError : 
        print("Http error")
        pass
    
5
  • You are returning to the loop, it just keep throwing URLError. Commented Jul 12, 2021 at 12:14
  • This is most likely caused by the fact that you're constraining the except clause with urllib.error.URLError exception. But your code can also raise Exceptions from JSON decodes... IF you want to pass ALL errors, then remove urllib.error.URLError. Commented Jul 12, 2021 at 12:20
  • @Xelvoz That is not what OP is asking, and catching all exceptions is a very bad practice Commented Jul 12, 2021 at 12:21
  • @DeepSpace That is true. It was a big "IF", but your solution seem most appropriate :) Commented Jul 12, 2021 at 12:24
  • Note that i += 1 is only executed if api.siret does not raise an exception. If you move that to a finally clause, you would actually proceed to the next URL (though you would still see "Http error" for each failing URL). Commented Jul 12, 2021 at 12:27

1 Answer 1

2

Since you have print("Http error") inside the except block, it will be executed every time the exception occurs.

Consider the more idiomatic approach below:

for siret in list_siret:
    try:
        data = api.siret(siret).get()
    except urllib.error.URLError:
        continue
    str_datajs = json.dumps(data, indent=4)
    a_json = json.loads(str_datajs)
    print("test1", i ,str_datajs)

We iterate directly over list_siret without needing to index into it and manually manage i, and instead of passing we just move to the next element in the list in case an exception was raised.

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

Comments

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.