KristiLuna
KristiLuna

Reputation: 1893

Python - try except with multiple possibilities

I'm trying the following:

try:
    scroll_token = response["scroll_token"]

except ValueError as e:
    logging.info(f'could not find "scroll_token" {e}')

    try:
        scroll_token = response["scroll_id"]
    except ValueError as e:
        logging.info(f'could not find "scroll_id" {e}')

Pretty much if the response doesn't have "scroll_token" in the response then I want it to see if there is "scroll_id" in the response instead. but for some reason this isn't working, it just keeps failing at the 1st try case and says:

scroll_token = response["scroll_token"] KeyError: 'scroll_token'

Upvotes: 0

Views: 41

Answers (1)

chepner
chepner

Reputation: 530922

You are catching the wrong exception; it's KeyError that you are expecting could be raised.

try:
    scroll_token = response["scroll_token"]

except KeyError as e:
    logging.info(f'could not find "scroll_token" {e}')

    try:
        scroll_token = response["scroll_id"]
    except KeyError as e:
        logging.info(f'could not find "scroll_id" {e}')

You can write this more simply with a loop.

for k in ["scroll_token", "scroll_id"]:
    try:
        scroll_token = response[k]
        break
    except KeyError:
        logging.info("could not find %s", k)
else:
    # What to do if neither key is found?
    ...

Upvotes: 1

Related Questions