How to continue execution after raising assertion error in selenium python - python

I have written the code as below.
If the element is displayed then it has to log the error message at the end of the complete execution
If the element not displayed then report the message as
"Not displayed"
try:
if self.driver.find_element(By.XPATH,"").is_displayed():
raise AssertionError("Element should not be displayed")
except NoSuchElementException:
self.log.info("Element not displayed")
If element displayed then raising the assertion error where execution will stop if the element does not exist then continuing the execution.
How can I write the script for both the conditions?

If I understood correctly, this is just a case of using the proper syntax. You don't need a try / except here. Using what you put in the question:
if self.driver.find_element(By.XPATH,"").is_displayed():
raise AssertionError("Element should not be displayed")
else:
self.log.info("Element not displayed")

use else
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally:
print("This will be printed irrespective of the outcome")

Related

How to continue with the execution even if i catch an error [duplicate]

This question already has answers here:
Catch exception and continue try block in Python
(12 answers)
Closed 11 months ago.
I want to control the error just printing it but continuing with the rest, por example:
try:
list =('a',2,3,5,6,'b',8)
print(list[8])
print("continue execution")
except:
print("An exception occurred")
It just will print the error but not the continue execution, is possible to continue even after exception?
What is missing and you're looking for is the finally instruction.
Syntax:
try:
#search for errors
except:
#if errors found, run this code
finally:
#run this code no matter if errors found or not, after the except block
The finally block contains the code that will be run after the except block, no matter if errors were raised or not.
See if this rearrangement of your own code helps:
list =('a',2,3,5,6,'b',8)
try:
print(list[8])
except:
print("An exception occurred")
print("continue execution")
If it matters for you to "print continue" right after exception occurrence , then you can put whatever you want to do before exception in a "bool function" and then inside the "try" check if function succeed or not.it means "if error occurred continue ,else show "An exception occurred".
try:
assert doStuff() == False
print("continue execution")
except:
print("An exception occurred")

Prevent exit on exception in Python

I am trying to catch an exception thrown by Selenium. When the exception is thrown I would like to restart the scraping process.
try:
startScraping(rootPage)
except (InvalidSessionIdException):
startScraping(rootPage)
finally:
driver.close()
Above is the code I am using.
The problem I am facing is that when an InvalidSessionIdException occurs the script still stops execution and shows a stacktrace.
the second startScraping(rootPage) (in the except block) is not protected by any try/except block...
If an exception occurs, retrying immediately is probably bound to fail ... again. I would
catch the exception
print a meaningful warning
wait a while
repeat until it works, or a given number of times with a for loop
like this
import time
nb_retries = 10
for nb_attempts in range(nb_retries):
try:
startScraping(rootPage)
break # success, exit the loop
except InvalidSessionIdException as e:
print("Warning: {}, attempt {}/{}".format(e,nb_attempts+1,nb_retries))
time.sleep(1)
else:
# loop went through after 10 attempts and no success
print("unable to scrape after {} retries".format(nb_retries))
driver.close()
Try this if you want to restart the process and ignoring the exception:
while True:
try:
startScraping(rootPage)
break # after finishing the scraping process
except (InvalidSessionIdException):
pass # or print the excepion
driver.close()
as mentioned in the code, you can print the exception or do any other exception handling you may want.

How to supress error printed out by try except block in python

I've a try except block within a try except block in python and I want to suppress the error message printed to the screen if the try block doesn't succeed. My code structure is as follows:
try:
#doing something
except Exception:
try:
#doing something else
except Exception:
print("Some message")
else:
print("Success")
else:
print("Success")
What happens right now is that an ERROR message gets printed to the screen by Python indicating what I'm doing in the try statement failed. I'm trying to find a way to suppress this.

If for Exception

I am teaching myself python and I am still an amateur at remembering all the keywords.
So; simple question, is there to way to use an if statement for an exception?
I can make the exception(NameError) print something. However, I want to use an if statement for if the exception is executed, then do this.
Help would be greatly appreciated!
try-except blocks were designed specifically for the purpose of catching exceptions. if statements are conditionals and are not designed to work with exceptions.
Here's a simple program to demonstrate exception handling:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException()
except SomeException:
print("In except block.")
Additionally, if you need information about the exception, you can use a special except block:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException()
except SomeException as exc: #exc is the exception object
print("In except block.")
When creating exceptions, you can optionally pass one or more arguments to indicate why the exception was raised:
class SomeException(Exception):
pass
try:
print("In try block.")
raise SomeException("message")
except SomeException as exc:
print(exc.args[0]) #Prints "message"
Here's a tutorial on exceptions that I found particularly useful.
A "try-except" block is exactly what you're looking for. Any code in the "try" part is executed normally, but if there's an exception, instead of returning back, it goes to the "except" block.
To phrase it how you were asking, any code in an "except" block runs IF the specific exception was raised/excecuted.
Instead of an error like this:
print(x)
NameError: name 'x' is not defined
You could do this:
try:
print(x)
except NameError:
print("error!")
error!
It will print "error!" IF anything in the try: block resulted in a NameError.
You can also use "else" and "finally" for more control.
Any code in the Else block runs if there were no errors.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong
Anything in a "finally" block runs after regardless of if there was an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Something went wrong
The 'try except' is finished
I recommend reading the W3 Schools page on Try Except.
https://www.w3schools.com/python/python_try_except.asp
Protip: you can do something like except Exception as e which will save info about the exception to e.

Python - Try/Except, what is ok and what is wrong?

I have to deal with a large quantity of try/except. I'm in doubt about the right way of doing it.
Option 1:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
Option 2:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
except RetryException, e:
SendMail.is_valid_problem(e)
In the Option 1, even is the exception is raised, "is_valid" will be tested and I don't need that.
In the Option 2, is what I think is correct but the code will look like a "callback hell".
What option should I choose or what option is the correct one?
Keep your exception handling as close as possible to the code that raises the exception. You don't want to accidentally mask a different problem in code you thought would not raise the same exception.
There is a third option here, use the else: suite of the try statement:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
else:
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
The else: suite is only executed if there was no exception raised in the try suite.
From your conditions, condition 1 is better and you can use else instead of if is_valid
Here are some of Try Except:
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
The except clause with multiple exceptions:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
The try-finally clause:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
I think option 1 is better. The reason is that you should always put inside a try except only the code which you expect to throw the exception. Putting more code increase the risk of catching an unwanted exception.
Make sure that if an Error will occur, keep the cause inside the try statement. That way, it will catch the error and sort it out in the except section. There is also finally. If the try doesn't work, but the "except" error doesn't work, it will act out the "finally" statement. If there is no finally, the program will get stuck. This is a sample code with try and except:
import sys
import math
while True:
x=sys.stdin.readline()
x=float(x)
try:
x=math.sqrt(x)
y=int(x)
if x!=y:
print("Your number is not a square number.")
elif x==y:
print("Your number is a square number.")
except(ValueError):
print("Your number is negative.")
ValueError is the error you get from sqrt-ing a negative number.

Categories

Resources