Home > other >  How to try-except block exit when try is working
How to try-except block exit when try is working

Time:01-30

The code I have works. The last for loop gets reached and choice.click() gets clicked on. The question I have is why the except block gets executed even though the:

            if choice.text == call_resource:
                choice.click()
                break

piece of the code is reached and the choice.click() portion works?

def select_choice(driver, resource_tag): 
    try:
        call_resource = None
        access_data = common.retrieve_tag_access_data()
        for row in access_data["access_data"]:
            if str(row["id"]) == resource_tag:
                call_resource = row["row_tag"]["name"]
                break
        if call_resource is None:
            access_data = common.retrieve_fixture_access_data()
            for row in access_data["access_data"]:
                if str(row["id"]) == resource_tag:
                    call_resource = row["row_tag"]["name"]
                    break
        menu = driver.find_element_by_css_selector("ul[role='listgrid']")
        choices = menu.find_elements_by_css_selector("li[role='choices']")
        for choice in choices:
            if choice.text == call_resource:
                choice.click()
                break
    except:
        error(logger, "unable to select choice")
        pass

Because the last for loop works, shouldn't it break entirely out of the function after choice.click() without executing the except: portion of the code?

CodePudding user response:

The except: portion will run only if an Exception occurred inside the try block. You should change the except: line to something like except Exception as e: and print the variable e in some way so you can discover what the problem is.

CodePudding user response:

choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
     if choice.text == call_resource:
        choice.click()
        break   

Could be replaced with since your only trying to click one element with a certain text why not just try to find it. If it errors out it will go to the exception you provided.

driver.find_element(By.XPATH,f"//li[@role='choices' and contains(text(),{call_resource})]").click()

Also use to find errors use the following.

except Exception as e:
    print(str(e))
                                   
  •  Tags:  
  • Related