1

Python except don't work. I'm trying

r = requests.get('URL') # URL returns something like: {"code": ["12345678"]} 
print(r.text)
parse = json.loads(r.text)

getcode = False
while not getcode:
    time.sleep(2)
    codeparse = parse["code"]
    print("Unable to get SMS Code, sleeping for 2 seconds...")
except KeyError:
    pass

getcode = parse["code"]

I've tried everything I know. Is there something I need to import or something I'm missing?

Edit: Updated to add more code as requested.

5
  • 2
    More code is necessary. There must be something going wrong. Also except KeyError is only going to detect KeyError. If you want it for all errors then use except Exception. But this will supress all error. Also, except should always go with try Commented Jun 27, 2021 at 14:55
  • It's impossible to see what the problem is with the given information. For all we know it might be an indentation issue...Please add a proper code snippet. Commented Jun 27, 2021 at 14:56
  • need at least try block and python version. Commented Jun 27, 2021 at 14:57
  • Please post your code here indented exactly as it is in your IDE, and post the exact error as python shows it Commented Jun 27, 2021 at 14:57
  • 2
    You have no try Commented Jun 27, 2021 at 15:04

3 Answers 3

1

I'm assuming that you're trying to read the value in the dictionary parse with key "code", and if there is no such entry, then you wait 2 seconds to try again.

Try this:

print(r.text)
parse = json.loads(r.text)

while True:
    try:
        codeparse = parse["code"]
        break
        
    except KeyError:
        print("Unable to get SMS Code, sleeping for 2 seconds...")
        time.sleep(2)

print("The value is", codeparse)
Sign up to request clarification or add additional context in comments.

Comments

1

This is simply invalid syntax: you can't have an except block as part of the while loop:

while not getcode:
    ...
except KeyError:
    pass

Example in the REPL:

>>> while 1:
...  print("g")
... except KeyError:
  File "<stdin>", line 3
    except KeyError:
    ^
SyntaxError: invalid syntax
>>>

So, you immediately get a SyntaxError, no matter what's inside the loop.

The proper syntax is:

try:
   # some code
   ...
except KeyError:
   ...

Comments

0

This is how the try except method works... Try some statement(s) and if it raises some error, then the except block will be run

try:
    print(0/0)
except KeyError:
    print('keyerror')
    '''in this block you can add what will happen if the error 
    raised in the try block raises an KeyError'''
except:
    print('some error occured')

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.