how to execute multiple conditions with try/catch in selenium webdriver - java

I am trying to execute a code that should give the output after verifying if any of the 6 conditions I define.
Is there any other way I can achieve that with try/catch method. Any other method is also appreciated.
This is the code I came up with so far:-
try {
if(drv.findElement(By.id("errorExplanation"))!= null){
System.out.println("Email already present");
}
}
catch (Exception e) {
if(drv.findElement(By.xpath("//*[#id='new_spree_user']/div[2]/div[4]/span"))!= null){
System.out.println("Issue in Email");
}
}
try {
if(drv.findElement(By.xpath("//*[#id='password-credentials']/span"))!=null){
System.out.println("Issue in Password");
}
}
catch (Exception e) {
if(drv.findElement(By.xpath("//*[#id='errorExplanation']/ul/li[2]"))!= null){
System.out.println("Empty Password");
}
}
Any help is greatly appreciated.

driver.findElement() will not return null if no element is found so your condition that checks that is not necessary. If no element is found, an exception is thrown which you are catching. You can avoid all the try/catches by using .findElements() (note the plural). If the element is not found, an empty list will be returned. You can then check for an empty list and avoid all the exceptions.
For example, here are the first couple... I'll let you do the rest.
if (!driver.findElements(By.id("errorExplanation")).isEmpty())
{
System.out.println("Email already present");
}
if (!driver.findElements(By.xpath("//*[#id='new_spree_user']/div[2]/div[4]/span")).isEmpty())
{
System.out.println("Issue in Email");
}

Related

if else?? try?? I need help on methods

If one method work and other doesn't then how do I make the code try a alternative method?
Here is the code
1st method
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
2nd method
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
If the first method doesn't work I want it to go ahead and try the second method but, I don't know what command to use for this.
I am not very experienced at programming so please bear with me.
You can use try catch block for this purpose :
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
catch (Exception e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
you can give a specific exception too, for example "ElementNotFoundException" or "ElementNotVisibleException" in your catch parameter type
I assume by "doesn't work" you mean the element wasn't found. Two options:
According to the documentation, findElement raises a NoSuchElementException if the element isn't found. So you can continue to use findElement and catch the exception via try/catch.
Alternately, use findElements, which returns a List, and branch based on whether any were found. As LuisGP pointed out, avoiding exceptions is often helpful.
Option 1:
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
Or if you meant to handle those one-by-one:
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
}
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/done")).click();
}
Option 2 (if you want to handle them one-by-one, you should be able to tweak if you want to branch on just the first result):
List<WebElement> elements;
elements = driver.findElements(By.id("com.simplemobiletools.gallery:id/dir_thumbnail"));
if (element.size() == 0) {
driver.findElement(By.id("com.offerup:id/circle")).click();
} else {
elements.get(0).click();
}
elements = driver.findElements(By.id("com.simplemobiletools.gallery:id/medium_thumbnail"));
if (elements.size() == 0) {
driver.findElement(By.id("com.offerup:id/done")).click();
} else {
elements.get(0).click();
}
You can try click on an element out of 4 given elements which is visible and clickable. It will make you to safe to clicking on element after catching exception and good practice to follow. It will throw exception only when no element will be found out of 4 and it is valid case.
MobileElement A = driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail"));
MobileElement B = driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail"));
MobileElement C = driver.findElement(By.id("com.offerup:id/circle"));
MobileElement D = driver.findElement(By.id("com.offerup:id/done"));
public void clickOnElement() {
try {
if(A.isDisplayed() && A.isEnabled())
{
A.click();
}
if(B.isDisplayed() && B.isEnabled())
{
B.click();
}
if(C.isDisplayed() && C.isEnabled())
{
C.click();
}
if(D.isDisplayed() && D.isEnabled())
{
D.click();
}
}catch (Exception e) {
e.printStackTrace();
}
}
Just call 'clickOnElement' method in your test case.

An exception is not thrown using throw command

I am coding a method that return an instance of FragmentManager as shown in the code belwo.
the prblem is, I want to throw an exception if the context passed to the method is null and then terminate the App.
what happens is, when I pass null to the method mentioned below, the App closes but the message in the NullPointerException which is :
getFragmentManagerInstance: Context reference is null
is not displayed
please let me know how to throw an exception and terminate the App correctly.
libs:
public static FragmentManager getFragmentManagerInstance(Activity activity) throws Exception {
try {
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
} catch (NullPointerException e) {
System.exit(1);
return null;
}
}
Just remove the try block. Simply typing
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
will do what you want, since NullPointerException is an unchecked exception.
The message "getFragmentManagerInstance: Context reference is null" is being stored in e. You need to print it to make it display on the screen.
In the catch block, add a print statement before System.exit(1)
catch (NullPointerException e) {
System.out.println(e);
System.exit(1);
return null;
}
is not displayed
Sure, that's because you're swallowing the exception:
} catch (NullPointerException e) {
System.exit(1);
return null;
}
The message is carried in e, and you're not using that in the catch block.
Note that it is almost never the right thing to do to catch a NullPointerException. In this case, you can simply print the message and terminate the app directly:
if (thing == null) {
System.err.println("It's null!");
System.exit(1);
}
Just use e.printStackTrace()
before System.exit(1)
and it will print as you wished
The message is not being displayed because you haven't written any code to print it. If you want to display message, add e.printStackTrace(); before exiting.
In order to print some information you need to provide them to an output stream such as System.out or System.err.
By default if you call ex.printstacktrace() it will print the exception within in System.err.
You can also use ex.printstacktrace(System.out) to choose where you send the information such as a file, the console or any output.
Also your application will immediately stop after the System.exit so your line of code need to be before the exit.
I'm suprised this hasn't been stated yet, change your catch block to
} catch(NullPointerException e){
System.err.print(e.getMessage());
System.exit(1);
return null;
}
And if you want to print a message to the user, consider using a Toast instead of Exception message.

Else condition not executed due to try catch

I have a scenario in which, when we click on save two process can occur. It can show some messages or else the page can crash. I have added an if condition for the crash and mentioned the other process if the application does not crash as else condition. I have written a code like this to handle the crash.
try {
if (driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div[1]/span[1]")).isDisplayed()){
System.out.println("Critical Error Occured.");
driver.close();
} else{
String msg = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div/div/div[1]/div/div[2]/div/div[1]/span")).getText();
if (msg.equals("User already registered")){
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
driver.close();
} else if (msg.equals("Admission number already exist.")) {
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
System.out.println("Please change the admission number.");
driver.quit();
} else if (msg.equals("Saved Successfully.")){
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
}
}
}catch ( org.openqa.selenium.NoSuchElementException e){
System.out.println("No Such Element Exception.");
}
Since the page crashes rarely, while executing the control goes to catch and so the else conditions for the first if condition is not executed. Is there any solution for this?
Do separate try-catch blocks inside the sections of the if or use a finally block for code you always want to execute.
You have two separate issues, the first is the findElement within the conditional. To handle that you need to do the find separately then do the if.
Element elem = null
try {
elem = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div[1]/span[1]"));
} catch (org.openqa.selenium.NoSuchElementException e) {
System.out.println("No Such Element Exception.");
}
Then after that you need to handle it within the else
if (elem != null && elem.isDisplayed()){
System.out.println("Critical Error Occured.");
driver.close();
} else{
try {
String msg = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div/div/div[1]/div/div[2]/div/div[1]/span")).getText();
if (msg.equals("User already registered")){
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
driver.close();
} else if (msg.equals("Admission number already exist.")) {
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
System.out.println("Please change the admission number.");
driver.quit();
} else if (msg.equals("Saved Successfully.")){
driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
System.out.println(msg);
}
} catch ( org.openqa.selenium.NoSuchElementException e){
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
May-be you're looking for the finally clause, aren't you ?
Finally clause can solve your problem. Its best practice to include must execute code in Finally clause

Selenium Webdriver: best practice to handle a NoSuchElementException

After much searching and reading, I'm still unclear as to the best way to handle a failed assertion using Webdriver. I would have thought this was a common and core piece of functionality. All I want to do is:
look for an element
if present - tell me
if not present - tell me
I want to present the results for a non technical audience, so having it throw 'NoSuchElementExceptions' with a full stack trace is not helpful. I simply want a nice message.
My test:
#Test
public void isMyElementPresent(){
// WebElement myElement driver.findElement(By.cssSelector("#myElement"));
if(driver.findElement(By.cssSelector("#myElement"))!=null){
System.out.println("My element was found on the page");
}else{
System.out.println("My Element was not found on the page");
}
}
I still get a NoSuchElementException thrown when I force a fail. Do I need a try/catch as well? Can I incorporate Junit assertions and/or Hamcrest to generate a more meaningful message without the need for a System.out.println?
I have encountered similar situations. According to the Javadoc for the findElement and findElements APIs, it appears that the findElement behavior is by design. You should use findElements to check for non-present elements.
Since in your case, there's a chance that the WebElement is not present, you should use findElements instead.
I'd use this as follows.
List<WebElement> elems = driver.findElements(By.cssSelector("#myElement"));
if (elems.size == 0) {
System.out.println("My element was not found on the page");
} else
System.out.println("My element was found on the page");
}
you can do something to check if element exists
public boolean isElementExists(By by) {
boolean isExists = true;
try {
driver.findElement(by);
} catch (NoSuchElementException e) {
isExists = false;
}
return isExists;
}
What about using an xPath inside of a try-catch, passing the elementype, attribute and text as follows?
try {
driver.FindElement(
By.XPath(string.Format("//{0}[contains(#{1}, '{2}')]",
strElemType, strAttribute, strText)));
return true;
}
catch (Exception) {
return false;
}
Even running it in a try block, it behaves as if unhandled,
neither of the catch blocks runs when the selenium exception occurs.
try {
wait.Until(webDriver => webDriver.PageSource.Contains(waitforTitle));
wait.Until(webDriver => webDriver.FindElement(By.Id(waitforControlName)).Displayed);
}
catch (OpenQA.Selenium.NoSuchElementException nse) {
nse = nse = null;
success = false;
}
catch (Exception ex) {
ex = ex = null;
success = false;
}

How to continue with If-Conditions in Try-Catch

I have this line of Code
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
}
It is possible, that only one of the three properties are set. But if one property isnt set, I get this NullpointerException. I catch it, but then the try-Block isnt continued.
So e.g. if the article.getTxtText() method returns null, I dont get the txtLongText and txtShortText Strings either, although at least one of them has a not empty String set.
So the question is, how can I continue the try-block although there's is an Exception caught?
Thanks a lot.
You should either use 3 try-catch blocks or just use a null-check around every case.
if (article.getTxtText() != null) {
// do part 1
}
if (article.getObjLongTextData() != null) {
// do part 2
}
I would imagine that the correct approach to this is to have three try/catch blocks around each point of code. The whole point of a try block is that you are trying the code as a lump and if it fails anywhere you abandon it. For what you are describing you would need three try/catches around each possible point of failure.
That having been said you are probably better off testing for null rather than relying on exception handling to do that. Exception handling should be for exceptionalm unforeseen events, not for flow control in a program.
If you must do this with exceptions (and I don't think you should), then you need to have 3 separate try/catch blocks:
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {}
Once an exception is thrown in your code you cannot restart execution in the middle of the try block.
Having said that I would always prefer to detect the null pointer with an if test rather than relying on exception handling for this non-exceptional condition.
do defensive programming ,check for nulls.
if ( variable != null ){
...
}
The simplest and better approach from my point of view would be break the try - catch block in three different try-catch block, something like the following :
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
//Handle Exception
}
I'd recommend a different design:
private void addProperty(Object property, Collection<String> properties) {
if (property == null) {
return;
}
String textProperty = property.toString();
if (StringUtils.hasText()) {
properties.add(textProperty);
}
}
Usage:
addProperty(article.getTxtText());
// ...
Why are you doing this in a try / catch, just use simple if
if ( txtText != null ){
...
}
if ( txtLongText != null ){
...
}

Categories

Resources