Python: Code not running during an exception within a loop - python

I am running a python code with a for loop iteration within a for loop, the code is working however, if an exception is thrown the code to execute under exception is not executing and the code loops inifinitely within the except without moving to the main loop
Error Message below:
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
from unknown error: web view not found
(Session info: chrome=73.0.3683.86)
(Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 10.0.17763 x86_64)
Code that I tried:
for _ in range(100):
print("main loop pass")
for button in fb_buttons:
driver.switch_to.window(driver.window_handles[1])
try:
while like_right:
for right in like_right:
right.click()
break
driver.switch_to.window(driver.window_handles[0])
except (NoSuchWindowException, ElementNotVisibleException, StaleElementReferenceException) as e:
driver.switch_to.window(driver.window_handles[0])
continue
except StaleElementReferenceException as e:
time.sleep(10)
refresh.click()
else:
time.sleep(5)
refresh.click()
print("refreshed")
Googling/documentation came up with nothing...and it strikes me as strange that selenium is fine throwing an exception but can't catch it.

This break below renders the following line unreachable:
break
driver.switch_to.window(driver.window_handles[0]) # <--- unreachable
Here is a small example of what you might be going for, note this code throws:
sequence = ['first', 'second', 'third']
def run_after_type_error_exception():
print("runs after type error")
def run_after_index_error_exception():
print("runs after index error")
Without breaks this code will catch both exceptions on the first iteration. Here you also have a for-else block. Note, that after the third iteration this code will Do something else.
for iteration in range(5):
for element in sequence:
try:
while sequence:
for character in element:
sequence.pop()
sequence[1].split() + 1
except (NameError, TypeError, ValueError) as e:
print(f"Caught first exception: {e}")
run_after_type_error_exception()
# break
except IndexError as e:
print(f"Caught exception {e}")
run_after_index_error_exception()
# break
else:
print("Do something else")
print(f"Current iteration: {iteration}")
Also, note time.sleep(is_in_seconds) so if your code behaves similarly to the above code (where it's in the else portion ~half of the time), then you'll be sleeping for ~4 minutes at least...

Related

python exception handling order

I am trying to handle an exception in order,
if the first exeption dosn't work it should run the second one, but in code if the 1st exception dosn't work it stop running
try:
driver.find_element_by_xpath(Newtweet_button).click() #tweet button
sleep(2)
except (ElementClickInterceptedException):
driver.find_element_by_xpath(cross_button).click()
driver.find_element_by_xpath(close_button2).click() #if tweet is repeated
sleep(2)
driver.find_element_by_xpath(Newtweet_button).click()
except (ElementClickInterceptedException):
sleep(2)
driver.find_element_by_xpath(Newtweet_button).click() #tweet button
sleep(2)
you cant except this ElementClickInterceptedException or any exception multiple times in the same try/except block.
you CANT do this:
try:
# stuff
except (ElementClickInterceptedException):
# stuff
except (ElementClickInterceptedException):
# stuff
instead you can use this method:
try:
# stuff
except ElementClickInterceptedException:
try:
# stuff
except ElementClickInterceptedException:
# stuff
(btw, parentheses are redundant in python in such situations, loops condition and conditions)
or this method (infinite loop that tries to find the element):
while True:
try:
driver.find_element_by_xpath(Newtweet_button).click()
# if the above works, then quit the exception block
break
except ElementClickInterceptedException:
# except and try again
pass
# and you can sleep here to slow the process
sleep(2)
honestly, i used this method with while True a lot of times, because its the best when trying to find a webelement that is not loaded yet.
of course, you can put a condition to stop the infinite searching when iterates more than a limit set by you.

Python debugging in eclipse stop on outer except block

I have nested exceptions handling in my code, when inner blocks do some stuff before re-raising the exception to upper layers.
Traceback always reports the line number that started the exception handling.
However, when running in UI debugger (Pydev/Eclipse) it stops on the outer exception block in some cases.
Consider the following code for example:
import sys
def f(a):
c=5/a
return c
def sub(d):
print("Entered sub(%d)" % d)
try:
print("Entered try #sub")
e = f(d)/(d-1)
return e
except:
print("Do some staff before re-raising the exception upwards")
raise
def main():
try:
print("Entered try #main")
d = int(sys.argv[1])
sub(d)
except:
print("Reached except block #main")
raise
if __name__ == '__main__':
main()
When running with argument = 0, the exception is caused at line#4 and the debugger stops on that line:
However, when running with argument = 1, the exception is caused at line#11 (as reported in the printed traceback) but the debugger stops at line#15.
Once the debugger stops at the incorrect location it is very difficult to watch internal variables and handle the error, especially when the code in the try block uses loops.
In Pydev->Manage Exceptions, I checked only the "suspend on uncaught exceptions".
There is a checkbox "Skip exceptions caught in same function" that seem related (because it seems like the debugger skipped the first exception in sub and stopped on "raise" statement which can be considered another exception in same function, although the documentation says that it should re-raise the same exception).
This checkbox is grayed out unless I first check "Suspend on caught exceptions*", but once enabling it the debugger gets stuck and does not stop anywhere...
Will appreciate your help.
-Moshe

Catch all exceptions except user abort

I have a script that catches all exceptions, which works great unless I want to abort the script manually (with control + c). In this case the abort command appears to be caught by the exception instead of quitting.
Is there a way to exclude this type of error from the exception? For example something as follows:
try:
do_thing()
except UserAbort:
break
except Exception as e:
print(e)
continue
You could just force to exit the program whenever the exception happens:
import sys
# ...
try:
do_thing()
except UserAbort:
break
except KeyboardInterrupt:
sys.exit()
pass
except Exception as e:
print(e)
continue

How to figure out how many exceptions raised python

I want to find out the number of raised exceptions and use it with if statement. To be more clear: If it raises more than 10 TimeoutException following one after another, print "There is a problem with website". I searched for it but I couldn't find anything. I hope there is a efficent way to do this.
Here is the code:
while True:
try:
browser.get("url")
return
except selenium.common.exceptions.TimeoutException:
print "Timeout"
What I want to do is: If it raises more than 10 Timeout exceptions, print "There is a problem with website"
Just keep track of the number of times the exception has been raised in a counter. Try something like:
count = 1
while True:
try:
browser.get("url")
except selenium.common.exceptions.TimeoutException:
count += 1
if count >= 10:
print 'There is a problem with website'
break

Break statement in finally block swallows exception

Consider:
def raiseMe( text="Test error" ):
raise Exception( text )
def break_in_finally_test():
for i in range(5):
if i==2:
try:
raiseMe()
except:
raise
else:
print "succeeded!"
finally:
print "testing this!"
break
if __name__=='__main__':
break_in_finally_test()
I expected to see Exception( "Test error" ) to be raised, but instead only "testing this" is printed. The intention, of course, was to call raiseMe() only once, no matter if we succeed or not - but if it raises an exception, I would have wanted to see that!
Why does break swallow the exception that I explicitly raise?
From https://docs.python.org/2.7/reference/compound_stmts.html#finally:
If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded
This also reflects the behaviour expected from the try...finally statement before PEP341:
This is how a try except finally block looked like pre PEP341:
try:
try:
raiseMe()
except:
raise
finally:
#here is where cleanup is supposed to happen before raising error
break
#after finally code: raise error
As the raising of errors never happens in the finally block it is never actually raised.
To maintain backwards compatibility with Python<=2.4, it had to be done in this way.
From the docs Error Handling Docs:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
Your exception never gets raised because you break before the try statement gets fully evaluated.
I think upon reflection that it is due to the fact that break actually raises a StopIteration to "break" out of the for-loop. This is really not very intuitive and not particularly well documented (not mentioned on 1, for example). Could maybe someone confirm/explain it better?
Have the following code structure:
def func():
try:
driver.do("something")
except TimeoutException:
pass
finally:
result = driver.do("something else")
return result
Got the exception by pylint:
return statement in finally block may swallow exception (lost-exception)
Solution was to put return out of the finally statement:
def func():
try:
driver.do("something")
except TimeoutException:
pass
finally:
result = driver.do("something else")
return result # <<

Categories