Home > Mobile >  try except, how to retry after exception error?
try except, how to retry after exception error?

Time:11-03

im trying to use try and expect to update some values from API this is the code which im using and i think its not working well, due to while its find error its filling all upcoming data with the same error value

`

new_budget = []
new_revenue = []
i = 42
start_time = time.time()
while len(new_budget) < 20:
    try:
        id = dfbudget['id'].iloc[i]
        response = tmdb.Movies(id).info()
        responsebdg = response['budget']
        new_budget.append(responsebdg)
        responservn = response['revenue']
        new_revenue.append(responservn)
        i  = 1
    except:
        new_budget.append('test')
        new_revenue.append('test')

`

Image from the result

how can i handle the error once receiving HTTPError filling the data with 0 and retry to the next checking value

CodePudding user response:

The issue is, when there's a HTTPError, the code flow jumps to the except block at that exact line. The code does not gets a chance to get to the 13th line where the i is getting incremented.

Since the value of i remains the same, it keeps on fetching the same value from the API and gets the same Error message for the rest of the loop.

So making sure that i increments, whether there's an error or not, would solve the problem. The following code should work.

new_budget = []
new_revenue = []
i = 42
start_time = time.time()
while len(new_budget) < 20:
    try:
        id = dfbudget['id'].iloc[i]
        response = tmdb.Movies(id).info()
        responsebdg = response['budget']
        new_budget.append(responsebdg)
        responservn = response['revenue']
        new_revenue.append(responservn)
    except:
        new_budget.append('0')
        new_revenue.append('0')
    i  = 1
  • Related