1

I am trying to use switch to alert and perform an action but i face error.

Now the real issue is when i put the below code in try,catch it works perfectly. i mean it handles the alert perfectly. But when i use the same without try, catch code it throws the below exception

  Alert alert = driver.switchTo().alert();
            String AlertText = alert.getText();
System.out.println(javascriptconfirm.getText());
            alert.accept();

Please find the error below

No alert is present (WARNING: The server did not provide any stacktrace information)
Sriram
  • 449
  • 3
  • 8
  • 15

1 Answers1

3

The idea is when you deal with alerts you have to check whether alert is present first. I would use this approach:

public boolean isAlertPresent() {

  boolean presentFlag = false;

  try {

   // Check the presence of alert
   Alert alert = driver.switchTo().alert();
   // Alert present; set the flag
   presentFlag = true;
   // if present consume the alert
   alert.accept();

  } catch (NoAlertPresentException ex) {
   // Alert not present
   ex.printStackTrace();
  }

  return presentFlag;

 }

here you can get details Also do not forget about debug step by step to get to know on what step alert appears/not appears. Hope this helps you.

eugene.polschikov
  • 7,254
  • 2
  • 31
  • 44
  • Correct. I used the same approach(try/catch) earlier and was able to handle it perfectly. Just wanted to know what goes wrong when u don't use a try/catch statement. I am marking this as an answer to add more meaning and to mark that this is one way of handling it. Thanks.. – Sriram Jun 14 '13 at 11:54