0

I want to repeat the for loop with the same variable when an exception occurred

    for Coin in coins: ['btc', 'eth']
        try:
            coin_s = get_data(Coin.lower())
            mining_stats = calc_reward(Coin)
        except decoder.JSONDecodeError:
            print('Too much requests')
            continue

Let's say the JSONDecodeError error happens in 'btc' but while handling the exception it jumps towards next item which is 'eth' is there any way to solve this?

196138105
  • 1
  • 1
  • 1
    You need a second nested loop to handle any "retry" logic. – 0x5453 Jul 13 '21 at 20:28
  • You could do something like this: https://stackoverflow.com/questions/4606919/in-python-try-until-no-error Instead of tracking success in a variable, keep track of an index into your coin types array and only increment on success. – StardustGogeta Jul 13 '21 at 20:28
  • what makes You think that repeating with the same variable won't raise an error again, because if that happens, well then ... You may get stuck in that loop forever. EDIT: I figured it would be possible to use some flag that would count the retries and if too many then just continue with the next – Matiiss Jul 13 '21 at 20:29

3 Answers3

1

Here is a basic solution:

attempts = 5
for obj in iterable:
    for _ in range(attempts):
        try:
            # code
            break
        except Exception as e:
            # print(e)
            pass

first of there needs to be a limit for the second loop (basically don't use a while True (although possible but that would require adding unnecessary variables that can be avoided using a for loop, basically I am saying that You shouldn't allow it to loop unconditionally)), otherwise it may run forever if the error persists

second, it is kind of important to print the error or except a specific error, otherwise You may not know why it actually throws an exception. So either You except Exception and then get to know what exception it was, for example there can be different exceptions so just so You know what went wrong, or have an expected exception (when You also don't need to print since You would know what was excepted (also instead of printing You could use some logging method))

obviously the attempts value can be changed

also to note _ variable in this case basically tells python to ignore it/throw away because it isn't used anyways (although possible to put say i and then print the attempt in the exception block (maybe that is helpful, again could use a logger instead of print))

also also reading one (or the only one) mentioned question in the comments under this question it said that a delay between attempts should also be added (could use time.sleep() method) however that was more meant for if code is related to servers and sending requests and stuff (which may be the case but try that out yourself (if You were to add time.sleep() I suggest adding it in the except block tho try out yourself))

Matiiss
  • 5,970
  • 2
  • 12
  • 29
1

Use a while loop.

Coin = next(Coins)
# infinite retries
while True:
    try:
        coin_s = get_data(Coin.lower())
        mining_stats = calc_reward(Coin)
    except decoder.JSONDecodeError:
        print('Too much requests')
        continue
    try:
        Coin = next(coins)
    except StopIteration:
        break

Add logic if you want to limit the number retries.

retry_limit = 3
n_retries = 0
Coin = next(Coins)
while True:
    try:
        coin_s = get_data(Coin.lower())
        mining_stats = calc_reward(Coin)
    except decoder.JSONDecodeError:
        print('Too much requests')
        if n_retries < retry_limit:
            n_retries += 1
            continue
        else:
            n_retries = 0
    try:
        Coin = next(coins)
    except StopIteration:
        break
wwii
  • 23,232
  • 7
  • 37
  • 77
0

You could use another "try except":

   for Coin in coins: ['btc', 'eth']
        try:
            coin_s = get_data(Coin.lower())
            mining_stats = calc_reward(Coin)
        except decoder.JSONDecodeError:
            print('Too much requests')
            try:
                # your code
            except:
                continue
marckesin
  • 71
  • 4
  • this is too repetitive, what if You wanted to try say 10 times? and had a large block of code to try? – Matiiss Jul 13 '21 at 20:33