Else condition not executed due to try catch - java

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

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.

how to terminate finally block and execute rest of the code outside the try...catch...finally block

public static void main(String[] args) {
try{
System.out.println("This is try block...!!");
}
catch(Exception e)
{
System.out.println("Exception is "+e);
}
finally
{
System.exit(0);//terminates finally block
System.out.println("This is finally block");
}
System.out.println("This is outside the try catch block...");
}
In above code i got output like this "This is try block...!!"
But i want output such that,
"This is try block...!!"
"This is outside the try catch block...!!"
can any one give me correct solution for this problem? and how can i get output as i want?does any one explain me please?
it's only for your situation if you want to skip execution of finally block when try is success.
boolean trySuccessflag = false;
try{
System.out.println("This is try block...!!");
trySuccessflag = true;
}
catch(Exception e)
{
System.out.println("Exception is "+e);
}
finally
{
if(!trySuccessflag){
System.out.println("This is finally block");
}
}
System.out.println("This is outside the try catch block...");
I think it may be so...
public static void main(String[] args) {
try{
System.out.println("This is try block...!!");
} catch(Exception e) {
System.out.println("Exception is "+e);
}
System.out.println ("This is outside the try catch block...");
}
Your "System.exit(0);" is before your "System.out.println ("This is outside the try catch block...")". So It doesn't work.
Remove this instruction :
System.exit(0);//terminates finally block
It stop the application not terminate the finally block
Your question has already an answer here
Your problem :
First you have to know that finally block is always executed, either you succeed or fail the try block.
Second, System.exit(0) exit the System. So the JVM. Not the Try block. So when you call your program simply terminates that's why nothing more is printed.
Solution :
First if you don't want to execute the Finally block, just do not write it. It makes no sense to write a code you don't want to execute.
Second, if you really need to exit the finally block use break; instead of System.exit(0);

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

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");
}

flow continue after exception catch

why flow continue after exception catch? when i click button, toast show me message but after flow continue....
I show you my code!
public static int showResult2(View v) {
int totalAmount = 0;
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
try {
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
}catch(NumberFormatException exc){
System.out.println(exc);
Toast.makeText(context, "inserisci una quantita' a \""+b.name, Toast.LENGTH_LONG).show();
break;
}
}
}
return totalAmount;
}
IN ANOTHER CLASS I RECALL THE METHOD:
ThreeFragment tf = new ThreeFragment();
string4 = tf.showResult(v);
try {
totalebibite = tf.showResult2(v);
} catch (NumberFormatException exc) {
exc.printStackTrace();
}
You've caught the exception, so Java assumes that you are going to deal with it adequately.
If you don't want that behaviour, aside from not catching it at all, you could always rethrow the exception (throw exc;) after you've printed your message, which means that something higher up the call stack ought to deal with it, or use a break; statement to end the loop early.
If you want to break your loop in exception use like the below.
You should add your break; in catch
break; is what you need to break out of any looping statement like for, while or do-while.
Still if it's comes meant make sure you are not calling this method again and again.
Also check in your Java class that you have any other method is using the same for loop condition.
You should not call your fragment classes. It's a wrong way to call a method.
ThreeFragment tf = new ThreeFragment();
string4 = tf.showResult(v);
totalebibite = tf.showResult2(v);
It's a static method call your method in this way
ThreeFragment.showResult2(v);
Check this showResult(v); has the same for loop
The below piece of code is similar to what you have presented. As pointed by others, break; ends the nearest loop.
for(int i=0; i<10; i++) {
if(true) {
try{
//Your logic here, which could throw exception
System.out.println("throwing");
if(true) {
throw new Exception("This is it");
}
}catch(Exception e){
System.out.println("catching");
break;
}
System.out.println("inside if");
}
System.out.println("inside for");
}
System.out.println("outside for");
Using break is a bad programming practice. You could change the flow of code to something like this.
try{
System.out.println("inside try");
for(int i=0; i<10; i++) {
if(true) {
if(true) {
throw new Exception("This is it");
}
System.out.println("inside if");
}
System.out.println("inside for");
}
}
catch(Exception e){
System.out.println("catching");
}
System.out.println("after catch");
Please mark your question as answered, if you see it is answered.
Put your try/catch block around the loop instead of inside, so the loop exits on an exception:
try {
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
}
}
} catch (NumberFormatException exc) {
System.out.println(exc);
Toast.makeText(context, "inserisci una quantita' a \""+b.name, Toast.LENGTH_LONG).show();
}
Alternatively, inside the catch block you can a) rethrow the exception, b) break out of the loop, or c) return from the method.

Selenium Webdriver Element not exists condition fails

I have a If Else block within a while block. If element is present, click it to remove it and put it back to parent list. Else if element is not in the list then select from parent list and put it back.
The first time it works. It sees that the element is present, clicks it to removes it. On the second pass it fails when checking for the element
I tried with FindElement.IsDisplayed and !=null.
I get this exception :
org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == select[id="idSelSelectedLanes"]>option[value="9012"] (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30.16 seconds
What am I missing?
This is my first post here so apologize for any formatting issues.
thanks
count ++;
if(count % 2 == 0){
if(BROWSER.equals("IE")) {
// check if 9012 is present
if(driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"))!=null){
try {
// since its present, click to remove
driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]")).click();;
Thread.sleep(1000);
} catch(NoSuchElementException e) {
System.out.println("Couldn't remove 9012");
}
} else {
try {
//Not present, so select from Available Lanes
driver.findElement(By.cssSelector("select[id=\"idSelAvailableLanes\"]>option[value=\"9012\"]")).isDisplayed();
} catch (NoSuchElementException e) {
System.out.println("Couldn't add 9012");
}
}
}
}
You need to put driver.findElement(...) in a try-catch block
count ++;
WebElement e;
if(count % 2 == 0) {
if(BROWSER.equals("IE")) {
// check if 9012 is present
try {
e = driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"));
Thread.sleep(1000);
e.click()
} catch (NoSuchElementException e) {
System.out.println("Couldn't remove 9012");
// the else part goes here
}
}
}
Another approach is to use findElements instead of findElement to avoid the try-catch, and use .get(0) to get the element you want.
Another solution, you should check elementExist first using findElements, if it exists -> perform other actions
count ++;
WebElement e;
String e9012Css = "select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]";
if(count % 2 == 0) {
if(BROWSER.equals("IE")) {
// check if 9012 is present
e9012Existed = driver.findElements(By.cssSelector(e9012Css)).size() > 0;
if(e9012Existed) {
driver.findElement(By.cssSelector(e9012Css)).Click();
}
}
else {
System.out.println("Couldn't remove 9012");
}
}
try to use isElementPresent
if(isElementPresent(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"))){
// since its present, click to remove
} else {
//Not present, so select from Available Lanes
}

Categories

Resources