-1
  try:
        if browser.find_element_by_xpath('//[@id="s"]/a').is_displayed():
            browser.find_element_by_xpath('//*[@id="s"]/a').click()
            browser.switch_to.default_content()
            browser.find_element_by_id('btn').click()
    except Exception as e:
        browser.find_element_by_id('btn').click()

The above code is to close a popup that is displayed on the page when I visit the first time. For the second iteration there is no popup.

I am using try and except statements to check for the popup close button and if close button present then close the popup and move forward with other actions, like - click a different button on the default page.

The except statement displays a Broad Exception warning in Pycharm IDE.

Do I use try except or do I just ignore the warning?

I've tried using if else instead of try and except, but it doesn't work. At this point I am not planning to capture any exceptions on the website.

  • "I've tried using if else instead of try and except, but it doesn't work. " what does it mean? What exactly have you tried? – Alexey R. Aug 17 '18 at 16:52
0

Don't use exceptions to control code business logic. It's a bad practice. Exceptions are used to handle the situations when something is going wrong. Better to use exceptions to handle situations when UI shows inconsistent state.

If there's no popup the second time and if it is designed in that way, then that cannot be an exceptional case. Moreover catching just a general exception will likely not be working as you expect since it will invoke the code whatever exception will be thrown. Not only the one you expect.

The better approach is to store the Boolean flag in your code showing if the popup should be shown and describe interaction depending on that flag. This will make your test more reliable and more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.