How To Handle Alerts Using Selenium WebDriver

There’s always a difficulty to handle Alerts in a Page.In that case we’ve to create a Method to handle alert and use Try and catch block.So that whenever an alert appears,it will handle.

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;

public class alerts_Ex

static FirefoxDriver fd=new FirefoxDriver();

public static boolean check_alert()
Alert a=fd.switchTo().alert();
String str=a.getText();
return true;
catch(Exception e)

System.out.println(“no alert”);
return false;
public static void main(String[] args)

fd.findElement(“find flights “)).click();
boolean x=check_alert();


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s