Ke.
Ke.

Reputation: 2586

Try Except Continue Python not working

I have the following try routine:

    While true:
    print("back to beginning")  
    self.driver.get("http://mylovelywebsite.com")
        try:
            wait.until(
                EC.title_is("This is my title")
            )
        except TimeoutException as ex:
            print("HERE!")
            print(ex.message)
            self.driver.quit()
            continue

It's for selenium, and it just waits to see if the title is there. However, I believe this is just a python problem (the selenium things are working fine)

The problem that happens is that the ex.message is not printing anything out. However, even when I remove this, it doesn't go to the .quit() function and when it reaches the continue statement it just goes back to the print("HERE!") statement (instead of going back to the beginning of the script.

I'm wondering how to make it so that when there is an error, it goes back to the beginning of the script and runs again? Do I have to put the continue and quit() 1 indent less? I'm not sure this would work though, because it would get to the continue statement even if the error wasnt catched.

Upvotes: 0

Views: 3726

Answers (1)

Filip Kilibarda
Filip Kilibarda

Reputation: 2668

  1. Your indentation is off.
  2. While should be while
  3. true should be True
  4. TimeoutException has no message attribute; Use str(ex) instead.
  5. You haven't shown if you've imported TimeoutException. Use from selenium.common.exceptions import TimeoutException

Correct formatting

from selenium.common.exceptions import TimeoutException

while True:
    print("back to beginning")  
    self.driver.get("http://mylovelywebsite.com")
    try:
        wait.until(EC.title_is("This is my title"))
    except TimeoutException as ex:
        print("HERE!")
        print(str(ex))
        self.driver.quit()
        continue

Sample program that kind of does what you describe

from selenium.common.exceptions import TimeoutException

timeOut = True 

while True:
    print("back to beginning")  
    try:
        if timeOut: 
            raise TimeoutException("Something caused a timeout")
        else:
            break # leave the while loop because no error occurred
    except TimeoutException as ex:
        print("HERE!")
        print(str(ex))
        continue

Infinite loop; terminate with ctrl+c.

Upvotes: 1

Related Questions