Best Selenium code snippet using org.openqa.selenium.WebDriverException.getMessage
org.openqa.selenium.WebDriverExceptionThe WebDriver error - unknown error, happens when the driver tries to process a command and an unspecified error occurs.
The error can generally be isolated to the specific driver. It is a good practice to read the error message for any pointers on why the error occurred.
The error message shows that Selenium webdriver is not able to focus on element. generally, it happens due to incompatibility between Browser and Driver versions

1Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot focus element
2  (Session info: chrome=61.0.3163.100)
3  (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
4Command duration or timeout: 0 milliseconds
5Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
6System info: host: 'DWA7DEVOS00170', ip: '10.96.162.167', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_25'
7Driver info: org.openqa.selenium.chrome.ChromeDriver
Here are code snippets that can help you understand more how developers are using
Source:ErrorHandlerTest.java  
...89    Response response = createResponse(ErrorCodes.UNHANDLED_ERROR);90    assertThatExceptionOfType(WebDriverException.class)91        .isThrownBy(() -> handler.throwIfResponseFailed(response, 123))92        .withNoCause()93        .withMessageContaining(new WebDriverException().getMessage());94  }95  @Test96  public void testShouldNotSetCauseIfResponseValueIsJustAString() {97    assertThatExceptionOfType(WebDriverException.class)98        .isThrownBy(() -> handler.throwIfResponseFailed(99            createResponse(ErrorCodes.UNHANDLED_ERROR, "boom"), 123))100        .withNoCause()101        .satisfies(expected -> assertThat(expected).isExactlyInstanceOf(WebDriverException.class))102        .withMessageContaining("boom")103        .withMessageContaining(new WebDriverException().getMessage());104  }105  @Test106  public void testCauseShouldBeAnUnknownServerExceptionIfServerOnlyReturnsAMessage() {107    assertThatExceptionOfType(WebDriverException.class)108        .isThrownBy(() -> handler.throwIfResponseFailed(109            createResponse(ErrorCodes.UNHANDLED_ERROR, ImmutableMap.of("message", "boom")), 123))110        .withNoCause()111        .withMessageContaining("boom")112        .withMessageContaining(new WebDriverException().getMessage());113  }114  @Test115  public void testCauseShouldUseTheNamedClassIfAvailableOnTheClassPath() {116    assertThatExceptionOfType(WebDriverException.class)117        .isThrownBy(() -> handler.throwIfResponseFailed(118            createResponse(ErrorCodes.UNHANDLED_ERROR,119                           ImmutableMap.of("message", "boom", "class", NullPointerException.class.getName())), 123))120        .withMessage(new WebDriverException("boom\nCommand duration or timeout: 123 milliseconds").getMessage())121        .withCauseInstanceOf(NullPointerException.class)122        .satisfies(expected -> assertThat(expected.getCause()).hasMessage("boom"));123  }124  @Test125  public void testCauseStackTraceShouldBeEmptyIfTheServerDidNotProvideThatInformation() {126    assertThatExceptionOfType(WebDriverException.class)127        .isThrownBy(() -> handler.throwIfResponseFailed(128            createResponse(ErrorCodes.UNHANDLED_ERROR,129                           ImmutableMap.of("message", "boom", "class", NullPointerException.class.getName())), 1234))130        .withMessage(new WebDriverException("boom\nCommand duration or timeout: 1.23 seconds").getMessage())131        .withCauseInstanceOf(NullPointerException.class)132        .satisfies(expected -> {133          assertThat(expected.getCause()).hasMessage("boom");134          assertThat(expected.getCause().getStackTrace()).isEmpty();135        });136  }137  @Test138  public void testShouldBeAbleToRebuildASerializedException() {139    RuntimeException serverError = new RuntimeException("foo bar baz!\nCommand duration or timeout: 123 milliseconds");140    assertThatExceptionOfType(WebDriverException.class)141        .isThrownBy(()-> handler.throwIfResponseFailed(142            createResponse(ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123))143        .withMessage(new WebDriverException(serverError.getMessage()).getMessage())144        .withCauseInstanceOf(serverError.getClass())145        .satisfies(expected -> {146          assertThat(expected.getCause().getMessage()).isEqualTo(serverError.getMessage());147          assertStackTracesEqual(expected.getCause().getStackTrace(), serverError.getStackTrace());148        });149  }150  @Test151  public void testShouldIncludeScreenshotIfProvided() {152    RuntimeException serverError = new RuntimeException("foo bar baz!");153    Map<String, Object> data = toMap(serverError);154    data.put("screen", "screenGrabText");155    assertThatExceptionOfType(WebDriverException.class)156        .isThrownBy(() -> handler.throwIfResponseFailed(157            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))158        .withMessage(new WebDriverException(159            serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds",160            new WebDriverException()).getMessage())161        .withCauseInstanceOf(ScreenshotException.class)162        .satisfies(expected -> {163          Throwable cause = expected.getCause();164          assertThat(((ScreenshotException) cause).getBase64EncodedScreenshot()).isEqualTo("screenGrabText");165          Throwable realCause = cause.getCause();166          assertThat(realCause).isNotNull();167          assertThat(realCause.getClass()).isEqualTo(serverError.getClass());168          assertThat(realCause.getMessage()).isEqualTo(serverError.getMessage());169          assertStackTracesEqual(serverError.getStackTrace(), realCause.getStackTrace());170        });171  }172  @Test173  public void testShouldDefaultToWebDriverExceptionIfClassIsNotSpecified() {174    RuntimeException serverError = new RuntimeException("foo bar baz!");175    Map<String, Object> data = toMap(serverError);176    data.remove("class");177    assertThatExceptionOfType(WebDriverException.class)178        .isThrownBy(() -> handler.throwIfResponseFailed(179            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))180        .withMessage(new WebDriverException(181            serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds",182            new WebDriverException()).getMessage())183        .withCauseInstanceOf(WebDriverException.class)184        .satisfies(expected -> {185          Throwable cause = expected.getCause();186          assertThat(cause.getMessage()).isEqualTo(new WebDriverException(serverError.getMessage()).getMessage());187          assertStackTracesEqual(serverError.getStackTrace(), cause.getStackTrace());188        });189  }190  @Test191  public void testShouldStillTryToBuildWebDriverExceptionIfClassIsNotProvidedAndStackTraceIsNotForJava() {192    Map<String, ?> data = ImmutableMap.of(193        "message", "some error message",194        "stackTrace", Collections.singletonList(195            ImmutableMap.of("lineNumber", 1224,196                            "methodName", "someMethod",197                            "className", "MyClass",198                            "fileName", "Resource.m")));199    assertThatExceptionOfType(WebDriverException.class)200        .isThrownBy(() -> handler.throwIfResponseFailed(201            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))202        .withMessage(new WebDriverException(203            "some error message\nCommand duration or timeout: 123 milliseconds",204            new WebDriverException()).getMessage())205        .withCauseInstanceOf(WebDriverException.class)206        .satisfies(expected -> {207          StackTraceElement[] expectedTrace = {208              new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224)209          };210          WebDriverException helper = new WebDriverException("some error message");211          helper.setStackTrace(expectedTrace);212          Throwable cause = expected.getCause();213          assertThat(cause.getMessage()).isEqualTo(helper.getMessage());214          assertStackTracesEqual(expectedTrace, cause.getStackTrace());215        });216  }217  @Test218  public void testToleratesNonNumericLineNumber() {219    Map<String, ?> data = ImmutableMap.of(220        "message", "some error message",221        "stackTrace", Collections.singletonList(222            ImmutableMap.of("lineNumber", "some string, might be empty or 'Not avalable'",223                            "methodName", "someMethod",224                            "className", "MyClass",225                            "fileName", "Resource.m")));226    assertThatExceptionOfType(WebDriverException.class)227        .isThrownBy(() -> handler.throwIfResponseFailed(228            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))229        .withMessage(new WebDriverException(230            "some error message\nCommand duration or timeout: 123 milliseconds",231            new WebDriverException()).getMessage())232        .withCauseInstanceOf(WebDriverException.class)233        .satisfies(expected -> {234          StackTraceElement[] expectedTrace = {235              new StackTraceElement("MyClass", "someMethod", "Resource.m", -1)236          };237          WebDriverException helper = new WebDriverException("some error message");238          helper.setStackTrace(expectedTrace);239          Throwable cause = expected.getCause();240          assertThat(cause.getMessage()).isEqualTo(helper.getMessage());241          assertStackTracesEqual(expectedTrace, cause.getStackTrace());242        });243  }244  @Test245  public void testToleratesNumericLineNumberAsString() {246    Map<String, ?> data = ImmutableMap.of(247        "message", "some error message",248        "stackTrace", Collections.singletonList(249            ImmutableMap.of("lineNumber", "1224", // number as a string250                            "methodName", "someMethod",251                            "className", "MyClass",252                            "fileName", "Resource.m")));253    assertThatExceptionOfType(WebDriverException.class)254        .isThrownBy(() -> handler.throwIfResponseFailed(255            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))256        .withMessage(new WebDriverException(257            "some error message\nCommand duration or timeout: 123 milliseconds",258            new WebDriverException()).getMessage())259        .withCauseInstanceOf(WebDriverException.class)260        .satisfies(expected -> {261          StackTraceElement[] expectedTrace = {262              new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224)263          };264          WebDriverException helper = new WebDriverException("some error message");265          helper.setStackTrace(expectedTrace);266          Throwable cause = expected.getCause();267          assertThat(cause.getMessage()).isEqualTo(helper.getMessage());268          assertStackTracesEqual(expectedTrace, cause.getStackTrace());269        });270  }271  @Test272  public void testShouldIndicateWhenTheServerReturnedAnExceptionThatWasSuppressed() {273    RuntimeException serverError = new RuntimeException("foo bar baz!");274    handler.setIncludeServerErrors(false);275    assertThatExceptionOfType(WebDriverException.class)276        .isThrownBy(() -> handler.throwIfResponseFailed(277            createResponse(ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123))278        .withNoCause()279        .withMessageContaining(serverError.getMessage())280        .withMessageContaining(new WebDriverException().getMessage());281  }282  @Test283  public void testShouldStillIncludeScreenshotEvenIfServerSideExceptionsAreDisabled() {284    RuntimeException serverError = new RuntimeException("foo bar baz!");285    Map<String, Object> data = toMap(serverError);286    data.put("screen", "screenGrabText");287    handler.setIncludeServerErrors(false);288    assertThatExceptionOfType(WebDriverException.class)289        .isThrownBy(() -> handler.throwIfResponseFailed(290            createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123))291        .withMessageStartingWith("foo bar baz!")292        .withCauseInstanceOf(ScreenshotException.class)293        .satisfies(expected -> {294          ScreenshotException screenshot = (ScreenshotException) expected.getCause();...Source:SeMethods.java  
...123				reportStep("The data: "+data+" entered successfully in field :"+ele, "PASS");124			} catch (InvalidElementStateException e) {125				reportStep("The element: "+ele+" is not interactable","FAIL");126			} catch (WebDriverException e) {127				reportStep("WebDriverException"+e.getMessage(), "FAIL");128			}129		}130131		public void click(WebElement ele) {132			String text = "";133			try {134				WebDriverWait wait = new WebDriverWait(driver,100);135			136				wait.until(ExpectedConditions.elementToBeClickable(ele));			137				text = ele.getText();138				ele.click();139				reportStep("The element : "+text+" is clicked "+text, "PASS");140			} catch (InvalidElementStateException e) {141				reportStep("The element: "+text+" is not interactable", "FAIL");142			} catch (WebDriverException e) {143				reportStep("WebDriverException"+e.getMessage(), "FAIL");144			} 145146		}147148		149		public void pressEnterKey(WebElement ele) {150		151			try {152				WebDriverWait wait = new WebDriverWait(driver, 10);153				wait.until(ExpectedConditions.elementToBeClickable(ele));			154				ele.sendKeys(Keys.ENTER);155				reportStep("Enter key is pressed", "PASS");156			} catch (InvalidElementStateException e) {157				reportStep("Enter key is not pressed", "FAIL");158			} catch (WebDriverException e) {159				reportStep("WebDriverException"+e.getMessage(), "FAIL");160			} 161			162		}163		164		public void clickWithNoSnap(WebElement ele) {165			String text = "";166			try {167				WebDriverWait wait = new WebDriverWait(driver, 10);168				wait.until(ExpectedConditions.elementToBeClickable(ele));	169				text = ele.getText();170				ele.click();171			//	switchToWindow(0);172			reportStep("The element :"+text+"  is clicked.", "PASS",false);173			} catch (InvalidElementStateException e) {174				reportStep("The element: "+text+" is not interactable", "FAIL",false);175			} catch (WebDriverException e) {176				reportStep("WebDriverException"+e.getMessage(), "FAIL",false);177			} 178		}179180		public String getText(WebElement ele) {	181			String bReturn = "";182			try {183				bReturn = ele.getText();184			} catch (WebDriverException e) {185				reportStep("WebDriverException"+e.getMessage(), "FAIL");186			}187			return bReturn;188		}189190		public String getTitle() {		191			String bReturn = "";192			try {193				bReturn =  driver.getTitle();194			} catch (WebDriverException e) {195				reportStep("WebDriverException"+e.getMessage(), "FAIL");196			} 197			return bReturn;198		}199200		public String getAttribute(WebElement ele, String attribute) {		201			String bReturn = "";202			try {203				bReturn=  ele.getAttribute(attribute);204			} catch (WebDriverException e) {205				reportStep("WebDriverException"+e.getMessage(), "FAIL");206			} 207			return bReturn;208		}209210		public void selectDropDownUsingText(WebElement ele, String value) {211			try {212				new Select(ele).selectByVisibleText(value);213				reportStep("The dropdown is selected with text "+value,"PASS");214			} catch (WebDriverException e) {215				reportStep("WebDriverException"+e.getMessage(), "FAIL");216			}217218		}219220		public void selectDropDownUsingIndex(WebElement ele, int index) {221			try {222				new Select(ele).selectByIndex(index);223				reportStep("The dropdown is selected with index "+index,"PASS");224			} catch (WebDriverException e) {225				reportStep("WebDriverException"+e.getMessage(), "FAIL");226			} 227228		}229230		public boolean verifyTitle(String expectedTitle) {231			boolean bReturn =false;232			try {233				if(getTitle().equals(expectedTitle)) {234					reportStep("The expected title matches the actual "+expectedTitle,"PASS");235					bReturn= true;236				}else {237					reportStep(getTitle()+" The expected title doesn't matches the actual "+expectedTitle,"FAIL");238				}239			} catch (WebDriverException e) {240				reportStep("WebDriverException : "+e.getMessage(), "FAIL");241			} 242			return bReturn;243244		}245246		public void verifyExactText(WebElement ele, String expectedText) {247			try {248				if(getText(ele).equals(expectedText)) {249					reportStep("The expected text matches the actual "+expectedText,"PASS");250				}else {251					reportStep("The expected text doesn't matches the actual "+expectedText,"FAIL");252				}253			} catch (WebDriverException e) {254				reportStep("WebDriverException : "+e.getMessage(), "FAIL");255			} 256257		}258259		public void verifyPartialText(WebElement ele, String expectedText) {260			try {261				if(getText(ele).contains(expectedText)) {262					reportStep("The expected text contains the actual "+expectedText,"PASS");263				}else {264					reportStep("The expected text doesn't contain the actual "+expectedText,"FAIL");265				}266			} catch (WebDriverException e) {267				reportStep("WebDriverException : "+e.getMessage(), "FAIL");268			} 269		}270271		public void verifyExactAttribute(WebElement ele, String attribute, String value) {272			try {273				if(getAttribute(ele, attribute).equals(value)) {274					reportStep("The expected attribute :"+attribute+" value matches the actual "+value,"PASS");275				}else {276					reportStep("The expected attribute :"+attribute+" value does not matches the actual "+value,"FAIL");277				}278			} catch (WebDriverException e) {279				reportStep("WebDriverException : "+e.getMessage(), "FAIL");280			} 281282		}283284		public void verifyPartialAttribute(WebElement ele, String attribute, String value) {285			try {286				if(getAttribute(ele, attribute).contains(value)) {287					reportStep("The expected attribute :"+attribute+" value contains the actual "+value,"PASS");288				}else {289					reportStep("The expected attribute :"+attribute+" value does not contains the actual "+value,"FAIL");290				}291			} catch (WebDriverException e) {292				reportStep("WebDriverException : "+e.getMessage(), "FAIL");293			}294		}295296		public void verifySelected(WebElement ele) {297			try {298				if(ele.isSelected()) {299					reportStep("The element "+ele+" is selected","PASS");300				} else {301					reportStep("The element "+ele+" is not selected","FAIL");302				}303			} catch (WebDriverException e) {304				reportStep("WebDriverException : "+e.getMessage(), "FAIL");305			}306		}307308		public void verifyDisplayed(WebElement ele) {309			try {310				if(ele.isDisplayed()) {311					reportStep("The element "+ele+" is visible","PASS");312				} else {313					reportStep("The element "+ele+" is not visible","FAIL");314				}315			} catch (WebDriverException e) {316				reportStep("WebDriverException : "+e.getMessage(), "FAIL");317			} 318		}319320		public void switchToWindow(int index) {321			try {322				Set<String> allWindowHandles = driver.getWindowHandles();323				List<String> allHandles = new ArrayList<>();324				allHandles.addAll(allWindowHandles);325				driver.switchTo().window(allHandles.get(index));326			} catch (NoSuchWindowException e) {327				reportStep("The driver could not move to the given window by index "+index,"PASS");328			} catch (WebDriverException e) {329				reportStep("WebDriverException : "+e.getMessage(), "FAIL");330			}331		}332333		public  void switchToFrame(WebElement ele) {334			try {335				//driver.switchTo().frame(ele);336				  WebDriverWait wait = new WebDriverWait(driver,100);337				  wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(ele));338				339				reportStep("switch In to the Frame "+ele,"PASS");340			} catch (NoSuchFrameException e) {341				reportStep("WebDriverException : "+e.getMessage(), "FAIL");342			} catch (WebDriverException e) {343				reportStep("WebDriverException : "+e.getMessage(), "FAIL");344			} 345		}346		347		348		public  void switchToMultipleFrames( String frame1, String frame2) {349			try {350				351				352				353				driver.switchTo().frame(frame1).switchTo().frame(frame2);354				355				356				357				reportStep("switch In to the Frame ","PASS");358			} catch (NoSuchFrameException e) {359				reportStep("WebDriverException : "+e.getMessage(), "FAIL");360			} catch (WebDriverException e) {361				reportStep("WebDriverException : "+e.getMessage(), "FAIL");362			} 363		}364		365366		public void acceptAlert() {367			String text = "";		368			try {369				Alert alert = driver.switchTo().alert();370				text = alert.getText();371				alert.accept();372				reportStep("The alert "+text+" is accepted.","PASS");373			} catch (NoAlertPresentException e) {374				reportStep("There is no alert present.","FAIL");375			} catch (WebDriverException e) {376				reportStep("WebDriverException : "+e.getMessage(), "FAIL");377			}  378		}379380		public void dismissAlert() {381			String text = "";		382			try {383				Alert alert = driver.switchTo().alert();384				text = alert.getText();385				alert.dismiss();386				reportStep("The alert "+text+" is dismissed.","PASS");387			} catch (NoAlertPresentException e) {388				reportStep("There is no alert present.","FAIL");389			} catch (WebDriverException e) {390				reportStep("WebDriverException : "+e.getMessage(), "FAIL");391			} 392393		}394395		public String getAlertText() {396			String text = "";		397			try {398				Alert alert = driver.switchTo().alert();399				text = alert.getText();400			} catch (NoAlertPresentException e) {401				reportStep("There is no alert present.","FAIL");402			} catch (WebDriverException e) {403				reportStep("WebDriverException : "+e.getMessage(), "FAIL");404			} 405			return text;406		}407		408		public void rightClickAction(WebElement ele) {409			try {410			Actions action = new Actions(driver);411			action.contextClick(ele).perform();412			reportStep("rightclick action is performed ","PASS");413			}catch (WebDriverException e) {414				reportStep("WebDriverException : "+e.getMessage(), "FAIL");415			}416		}417		418public void doubleClickAction(WebElement ele) {419	try {		420	Actions action = new Actions(driver);421	422	action.doubleClick(ele).perform();423	reportStep("DoubleClick action is performed ","PASS");424	}425	catch (WebDriverException e) {426		reportStep("WebDriverException : "+e.getMessage(), "FAIL");427	}428}429public void explicitWait(WebElement ele) {430		try {		431			WebDriverWait wait=new WebDriverWait(driver, 20);432			wait.until(ExpectedConditions.visibilityOf(ele));433			434		reportStep("The element is waited for 20 secs ","PASS");435		}436		catch (WebDriverException e) {437			reportStep("WebDriverException : "+e.getMessage(), "FAIL");438		}439}440			441		442443public void uploadDocument(String attachment) throws Throwable {444	try {445	String path = System.getProperty("user.dir");446	String filename = path+"\\documentstoupload\\"+attachment;447	 // Setting clipboard with file location448	 StringSelection stringSelection = new StringSelection(filename);449	 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);450	 // native key strokes for CTRL, V and ENTER keys451	 Robot robot = new Robot();452	 robot.keyPress(KeyEvent.VK_CONTROL);453	 Thread.sleep(1000);454	 robot.keyPress(KeyEvent.VK_V);455	 robot.keyRelease(KeyEvent.VK_V);456	 Thread.sleep(2000);457	 robot.keyRelease(KeyEvent.VK_CONTROL);458	 robot.keyPress(KeyEvent.VK_ENTER);459	 Thread.sleep(1000);460	 robot.keyRelease(KeyEvent.VK_ENTER);461	 reportStep("Document from local system has been attached ","PASS");462	}463	catch (WebDriverException e) {464		reportStep("WebDriverException : "+e.getMessage(), "FAIL");465	}466	467	468	469}470		471		472473		public long takeSnap(){474			long number = (long) Math.floor(Math.random() * 900000000L) + 10000000L; 475			try {476				String path = System.getProperty("user.dir");477				FileUtils.copyFile(driver.getScreenshotAs(OutputType.FILE) , new File(path+"//reports//images//"+number+".jpg"));478			} catch (WebDriverException e) {
...Source:BrowserActions.java  
...313			} else {314				reportStep("The element "+ele+" is not selected","FAIL");315			}316		} catch (WebDriverException e) {317			reportStep("WebDriverException : "+e.getMessage(), "FAIL");318		}319	}320	public void verifyDisplayed(WebElement ele) {321		try {322			if(ele.isDisplayed()) {323				reportStep("The element "+ele+" is visible","PASS");324			} else {325				reportStep("The element "+ele+" is not visible","FAIL");326			}327		} catch (WebDriverException e) {328			reportStep("WebDriverException : "+e.getMessage(), "FAIL");329		} 330	}331	public void switchToWindow(int index) {332		try {333			Set<String> allWindowHandles = driver.getWindowHandles();334			List<String> allHandles = new ArrayList<>();335			allHandles.addAll(allWindowHandles);336			driver.switchTo().window(allHandles.get(index));337		} catch (NoSuchWindowException e) {338			reportStep("The driver could not move to the given window by index "+index,"PASS");339		} catch (WebDriverException e) {340			reportStep("WebDriverException : "+e.getMessage(), "FAIL");341		}342	}343	public void switchToFrame(WebElement ele) {344		try {345			webDriverWait4FrameToBeAvailableAndSwitchTo(ele);346			reportStep("switch In to the Frame "+ele,"PASS");347		} catch (NoSuchFrameException e) {348			reportStep("WebDriverException : "+e.getMessage(), "FAIL");349		} catch (WebDriverException e) {350			reportStep("WebDriverException : "+e.getMessage(), "FAIL");351		} 352	}353	354	public void switchToFrame(int index) {355		try {356			webDriverWait4FrameToBeAvailableAndSwitchTo(index);357			reportStep("switch In to the Frame "+index,"PASS");358		} catch (NoSuchFrameException e) {359			reportStep("WebDriverException : "+e.getMessage(), "FAIL");360		} catch (WebDriverException e) {361			reportStep("WebDriverException : "+e.getMessage(), "FAIL");362		} 363	}364	365	public void switchToDefaultContent() {366		try {367			driver.switchTo().defaultContent();}368		catch (WebDriverException e) {369			reportStep("WebDriverException : "+e.getMessage(), "FAIL");370		} 371	}372	373	public void acceptAlert() {374		String text = "";		375		try {376			Alert alert = driver.switchTo().alert();377			text = alert.getText();378			alert.accept();379			reportStep("The alert "+text+" is accepted.","PASS");380		} catch (NoAlertPresentException e) {381			reportStep("There is no alert present.","FAIL");382		} catch (WebDriverException e) {383			reportStep("WebDriverException : "+e.getMessage(), "FAIL");384		}  385	}386	public void dismissAlert() {387		String text = "";		388		try {389			Alert alert = driver.switchTo().alert();390			text = alert.getText();391			alert.dismiss();392			reportStep("The alert "+text+" is dismissed.","PASS");393		} catch (NoAlertPresentException e) {394			reportStep("There is no alert present.","FAIL");395		} catch (WebDriverException e) {396			reportStep("WebDriverException : "+e.getMessage(), "FAIL");397		} 398	}399	public String getAlertText() {400		String text = "";		401		try {402			Alert alert = driver.switchTo().alert();403			text = alert.getText();404		} catch (NoAlertPresentException e) {405			reportStep("There is no alert present.","FAIL");406		} catch (WebDriverException e) {407			reportStep("WebDriverException : "+e.getMessage(), "FAIL");408		} 409		return text;410	}411	public void closeActiveBrowser() {412		try {413			driver.close();414			reportStep("The browser is closed","PASS", false);415		} catch (Exception e) {416			reportStep("The browser could not be closed","FAIL", false);417		}418	}419	public void closeAllBrowsers() {420		try {421			driver.quit();...Source:BaseClass.java  
...238			} else {239				reportStep("The element "+ele+" is not selected","FAIL");240			}241		} catch (WebDriverException e) {242			reportStep("WebDriverException : "+e.getMessage(), "FAIL");243		}244	}245	public void verifyDisplayed(WebElement ele) {246		try {247			if(ele.isDisplayed()) {248				reportStep("The element "+ele+" is visible","PASS");249			} else {250				reportStep("The element "+ele+" is not visible","FAIL");251			}252		} catch (WebDriverException e) {253			reportStep("WebDriverException : "+e.getMessage(), "FAIL");254		} 255	}256	public void switchToWindow(int index) {257		try {258			Set<String> allWindowHandles = driver.getWindowHandles();259			List<String> allHandles = new ArrayList<>();260			allHandles.addAll(allWindowHandles);261			driver.switchTo().window(allHandles.get(index));262		} catch (NoSuchWindowException e) {263			reportStep("The driver could not move to the given window by index "+index,"PASS");264		} catch (WebDriverException e) {265			reportStep("WebDriverException : "+e.getMessage(), "FAIL");266		}267	}268	public void switchToFrame(WebElement ele) {269		try {270			driver.switchTo().frame(ele);271			reportStep("switch In to the Frame "+ele,"PASS");272		} catch (NoSuchFrameException e) {273			reportStep("WebDriverException : "+e.getMessage(), "FAIL");274		} catch (WebDriverException e) {275			reportStep("WebDriverException : "+e.getMessage(), "FAIL");276		} 277	}278	public void acceptAlert() {279		String text = "";		280		try {281			Alert alert = driver.switchTo().alert();282			text = alert.getText();283			alert.accept();284			reportStep("The alert "+text+" is accepted.","PASS");285		} catch (NoAlertPresentException e) {286			reportStep("There is no alert present.","FAIL");287		} catch (WebDriverException e) {288			reportStep("WebDriverException : "+e.getMessage(), "FAIL");289		}  290	}291	public void dismissAlert() {292		String text = "";		293		try {294			Alert alert = driver.switchTo().alert();295			text = alert.getText();296			alert.dismiss();297			reportStep("The alert "+text+" is dismissed.","PASS");298		} catch (NoAlertPresentException e) {299			reportStep("There is no alert present.","FAIL");300		} catch (WebDriverException e) {301			reportStep("WebDriverException : "+e.getMessage(), "FAIL");302		} 303	}304	public String getAlertText() {305		String text = "";		306		try {307			Alert alert = driver.switchTo().alert();308			text = alert.getText();309		} catch (NoAlertPresentException e) {310			reportStep("There is no alert present.","FAIL");311		} catch (WebDriverException e) {312			reportStep("WebDriverException : "+e.getMessage(), "FAIL");313		} 314		return text;315	}316	public long takeSnap(){317		long number = (long) Math.floor(Math.random() * 900000000L) + 10000000L; 318		try {319			FileUtils.copyFile(driver.getScreenshotAs(OutputType.FILE) , new File("./reports/images/"+number+".jpg"));320		} catch (WebDriverException e) {321			System.out.println("The browser has been closed.");322		} catch (IOException e) {323			System.out.println("The snapshot could not be taken");324		}325		return number;326	}...Source:SeleniumBase.java  
...176			} else {177				reportStep("The element "+ele+" is not visible","fail");178			}179		} catch (WebDriverException e) {180			System.out.println("WebDriverException : "+e.getMessage());181		} 182		return false;183	}184	@Override185	public boolean verifyDisappeared(WebElement ele) {186		return false;187	}188	@Override189	public boolean verifyEnabled(WebElement ele) {190		try {191			if(ele.isEnabled()) {192				reportStep("The element "+ele+" is Enabled","pass");193				return true;194			} else {195				reportStep("The element "+ele+" is not Enabled","fail");196			}197		} catch (WebDriverException e) {198			System.out.println("WebDriverException : "+e.getMessage());199		}200		return false;201	}202	@Override203	public void verifySelected(WebElement ele) {204		try {205			if(ele.isSelected()) {206				reportStep("The element "+ele+" is selected","pass");207				//				return true;208			} else {209				reportStep("The element "+ele+" is not selected","fail");210			}211		} catch (WebDriverException e) {212			System.out.println("WebDriverException : "+e.getMessage());213		}214		//		return false;215	}216	@Override217	public RemoteWebDriver startApp(String url) {218		return startApp("chrome", url);219	}220	@Override221	public RemoteWebDriver startApp(String browser, String url) {222		try {223			if(browser.equalsIgnoreCase("chrome")) {224				System.setProperty("webdriver.chrome.driver",225						"./drivers/chromedriver.exe");226				driver = new ChromeDriver();227			} else if(browser.equalsIgnoreCase("firefox")) {228				System.setProperty("webdriver.gecko.driver",229						"./drivers/geckodriver.exe");230				driver = new FirefoxDriver();231			} else if(browser.equalsIgnoreCase("ie")) {232				System.setProperty("webdriver.ie.driver",233						"./drivers/IEDriverServer.exe");234				driver = new InternetExplorerDriver();235			}236			driver.navigate().to(url);237			driver.manage().window().maximize();238			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);239		} catch (Exception e) {240			reportStep("The Browser Could not be Launched. Hence Failed", "fail");241			throw new RuntimeException();242		} 243		return driver;244	}245	@Override246	public WebElement locateElement(String locatorType, String value) {247		try {248			switch(locatorType.toLowerCase()) {249			case "id": return driver.findElementById(value);250			case "name": return driver.findElementByName(value);251			case "class": return driver.findElementByClassName(value);252			case "link": return driver.findElementByLinkText(value);253			case "xpath": return driver.findElementByXPath(value);254			}255		} catch (NoSuchElementException e) {256			reportStep("The Element with locator:"+locatorType+" Not Found with value: "+value, "fail");257			throw new RuntimeException();258		}catch (Exception e) {259			reportStep("The Element with locator:"+locatorType+" Not Found with value: "+value, "fail");260		}261		return null;262	}263	@Override264	public WebElement locateElement(String value) {265		WebElement findElementById = driver.findElementById(value);266		return findElementById;267	}268	@Override269	public List<WebElement> locateElements(String type, String value) {270		try {271			switch(type.toLowerCase()) {272			case "id": return driver.findElementsById(value);273			case "name": return driver.findElementsByName(value);274			case "class": return driver.findElementsByClassName(value);275			case "link": return driver.findElementsByLinkText(value);276			case "xpath": return driver.findElementsByXPath(value);277			}278		} catch (NoSuchElementException e) {279			System.err.println("The Element with locator:"+type+" Not Found with value: "+value);280			throw new RuntimeException();281		}282		return null;283	}284	@Override285	public void switchToAlert() {286		driver.switchTo().alert();287	}288	@Override289	public void acceptAlert() {290		String text = "";		291		try {292			wait = new WebDriverWait(driver, 10);293			wait.until(ExpectedConditions.alertIsPresent());294			Alert alert = driver.switchTo().alert();295			text = alert.getText();296			alert.accept();297			reportStep("The alert "+text+" is accepted.", "pass");298		} catch (NoAlertPresentException e) {299			reportStep("There is no alert present.", "fail");300		} catch (WebDriverException e) {301			System.out.println("WebDriverException : "+e.getMessage());302		}  303	}304	@Override305	public void dismissAlert() {306		String text = "";		307		try {308			Alert alert = driver.switchTo().alert();309			text = alert.getText();310			alert.dismiss();311			System.out.println("The alert "+text+" is accepted.");312		} catch (NoAlertPresentException e) {313			System.out.println("There is no alert present.");314		} catch (WebDriverException e) {315			System.out.println("WebDriverException : "+e.getMessage());316		}  317	}318	@Override319	public String getAlertText() {320		String text = "";		321		try {322			Alert alert = driver.switchTo().alert();323			text = alert.getText();324		} catch (NoAlertPresentException e) {325			System.out.println("There is no alert present.");326		} catch (WebDriverException e) {327			System.out.println("WebDriverException : "+e.getMessage());328		} 329		return text;330	}331	@Override332	public void typeAlert(String data) {333		driver.switchTo().alert().sendKeys(data);334	}335	@Override336	public void switchToWindow(int index) {337		try {338			Set<String> allWindows = driver.getWindowHandles();339			List<String> allhandles = new ArrayList<String>(allWindows);340			String exWindow = allhandles.get(index);341			driver.switchTo().window(exWindow);...Source:SeleniumWrapper.java  
...244		} else {245			reportStep("The element "+ele+" is not selected","FAIL");246		}247	} catch (WebDriverException e) {248		reportStep("WebDriverException : "+e.getMessage(), "FAIL");249	}250}251public void verifyDisplayed(WebElement ele) {252	try {253		if(ele.isDisplayed()) {254			reportStep("The element is visible","PASS");255		} else {256			reportStep("The element is not visible","FAIL");257		}258	} catch (WebDriverException e) {259		reportStep("WebDriverException : "+e.getMessage(), "FAIL");260	} 261}262public boolean verifyDisplayedwithReturn(WebElement ele) {263	boolean result = false;264	try {265		if(ele.isDisplayed()) { 266			reportStep("The element is visible","PASS");267			result = true;268			return result;269		} else {270			reportStep("The element is not visible","FAIL");271			return result;272		}273	} catch (WebDriverException e) {274		reportStep("WebDriverException : "+e.getMessage(), "FAIL");275	}276	return result;277}278public void switchToWindow(int index) {279	try {280		Set<String> allWindowHandles = getDriver().getWindowHandles();281		List<String> allHandles = new ArrayList<>(); 282		allHandles.addAll(allWindowHandles);283		getDriver().switchTo().window(allHandles.get(index));284	} catch (NoSuchWindowException e) {285		reportStep("The getDriver() could not move to the given window by index "+index,"PASS");286	} catch (WebDriverException e) {287		reportStep("WebDriverException : "+e.getMessage(), "FAIL");288	}289}290public void switchToFrame(WebElement ele) {291	try {292		getDriver().switchTo().frame(ele);293		reportStep("switch In to the Frame "+ele,"PASS");294	} catch (NoSuchFrameException e) {295		reportStep("WebDriverException : "+e.getMessage(), "FAIL");296	} catch (WebDriverException e) {297		reportStep("WebDriverException : "+e.getMessage(), "FAIL");298	} 299}300public void acceptAlert() {301	String text = "";		302	try {303		Alert alert = getDriver().switchTo().alert();304		text = alert.getText();305		alert.accept();306		reportStep("The alert "+text+" is accepted.","PASS");307	} catch (NoAlertPresentException e) {308		reportStep("There is no alert present.","FAIL");309	} catch (WebDriverException e) {310		reportStep("WebDriverException : "+e.getMessage(), "FAIL");311	}  312}313public void dismissAlert() {314	String text = "";		315	try {316		Alert alert = getDriver().switchTo().alert();317		text = alert.getText();318		alert.dismiss();319		reportStep("The alert "+text+" is dismissed.","PASS");320	} catch (NoAlertPresentException e) {321		reportStep("There is no alert present.","FAIL");322	} catch (WebDriverException e) {323		reportStep("WebDriverException : "+e.getMessage(), "FAIL");324	} 325}326public String getAlertText() {327	String text = "";		328	try {329		Alert alert = getDriver().switchTo().alert();330		text = alert.getText();331	} catch (NoAlertPresentException e) {332		reportStep("There is no alert present.","FAIL");333	} catch (WebDriverException e) {334		reportStep("WebDriverException : "+e.getMessage(), "FAIL");335	} 336	return text;337}338public void closeActiveBrowser() {339	try {340		getDriver().close();341		reportStep("The browser is closed","PASS", false);342	} catch (Exception e) {343		reportStep("The browser could not be closed","FAIL", false);344	}345}346public void closeAllBrowsers() {347	try {348		getDriver().quit();...Source:SeleniumHelper.java  
...233			} else {234				reportStep("The element "+ele+" is not selected","fail");235			}236		} catch (WebDriverException e) {237			reportStep("WebDriverException : "+e.getMessage(), "fail");238		}239	}240	public void verifyDisplayed(WebElement ele) throws IOException {241		try {242			if(ele.isDisplayed()) {243				244				reportStep("The element "+ele+" is visible","pass");245			} else {246				reportStep("The element "+ele+" is not visible","fail");247			}248		} catch (WebDriverException e) {249			reportStep("WebDriverException : "+e.getMessage(), "f");250		} 251	}252	public void switchToWindow(int index) throws IOException, InterruptedException {253		try {254			Set<String> allWindowHandles = driver.getWindowHandles();255			List<String> allHandles = new ArrayList<>();256			allHandles.addAll(allWindowHandles);257			driver.switchTo().window(allHandles.get(index));258			Thread.sleep(3000);259			260		} catch (NoSuchWindowException e) {261			reportStep("The driver could not move to the given window by index "+index,"pass");262		} catch (WebDriverException e) {263			reportStep("WebDriverException : "+e.getMessage(), "fail");264		}265	}266	public void switchToFrame(WebElement ele) throws IOException {267		try {268			driver.switchTo().frame(ele);269			270			reportStep("switch In to the Frame "+ele,"pass");271		} catch (NoSuchFrameException e) {272			reportStep("WebDriverException : "+e.getMessage(), "fail");273		} catch (WebDriverException e) {274			reportStep("WebDriverException : "+e.getMessage(), "fail");275		} 276	}277	278	public void switchToFrame(String id) {279		try {280			driver.switchTo().frame(id);281			282			reportStep("switch In to the Frame "+id,"pass");283		} catch (NoSuchFrameException e) {284			reportStep("WebDriverException : "+e.getMessage(), "fail");285		} catch (WebDriverException e) {286			reportStep("WebDriverException : "+e.getMessage(), "fail");287		} 288	}289	public void acceptAlert() throws IOException {290		String text = "";		291		try {292			Alert alert = driver.switchTo().alert();293			text = alert.getText();294			alert.accept();295			reportStep("The alert "+text+" is accepted.","pass");296		} catch (NoAlertPresentException e) {297			reportStep("There is no alert present.","fail");298		} catch (WebDriverException e) {299			reportStep("WebDriverException : "+e.getMessage(), "fail");300		}  301	}302	public void dismissAlert() throws IOException {303		String text = "";		304		try {305			Alert alert = driver.switchTo().alert();306			text = alert.getText();307			alert.dismiss();308			reportStep("The alert "+text+" is dismissed.","pass");309		} catch (NoAlertPresentException e) {310			reportStep("There is no alert present.","fail");311		} catch (WebDriverException e) {312			reportStep("WebDriverException : "+e.getMessage(), "fail");313		} 314	}315	public String getAlertText() throws IOException {316		String text = "";		317		try {318			Alert alert = driver.switchTo().alert();319			text = alert.getText();320		} catch (NoAlertPresentException e) {321			reportStep("There is no alert present.","fail");322		} catch (WebDriverException e) {323			reportStep("WebDriverException : "+e.getMessage(), "fail");324		} 325		return text;326	}327	public void  takeSnap() throws InterruptedException {328		File src = driver.getScreenshotAs(OutputType.FILE);329		String path=System.getProperty("user.dir")+"/img"+System.currentTimeMillis()+".png";330		File des = new File(path);331		try {332			FileUtils.copyFile(src, des);333			Thread.sleep(3000);334			test.addScreenCaptureFromPath(path);335		} catch (IOException e) {336			System.err.println("IOException");337		}...Source:PopUpHandler.java  
...40				alert = driver.switchTo().alert();41				logger.info("Switching to Alert........");42			}43		} catch (WebDriverException e) {44			logger.error("Unable to switch to the alert.\n" + e.getMessage());45			throw new WebDriverException("Unable to switch to the alert.\n" + e);46		}47		if (waitForElement != null && waitForElement.length > 0) {48			setWebDriverWait(waitForElement[0]);49		}50		return alert;5152	}5354	public void acceptAlert(WebElement... waitForElement) {55		try {56			if (isAlertPresent()) {57				Alert alert = driver.switchTo().alert();58				alert.accept();59			}60		} catch (WebDriverException e) {61			logger.error("Unable accept the alert \n " + e.getMessage());62			throw new WebDriverException("Unable accept the alert \n " + e);63		}64		if (waitForElement != null && waitForElement.length > 0) {65			setWebDriverWait(waitForElement[0]);66		}67	}6869	public void dismissAlert(WebElement... waitForElement) {70		try {71			driver.switchTo().defaultContent();72			if (isAlertPresent()) {73				Alert alert = driver.switchTo().alert();74				alert.dismiss();75			}76		} catch (WebDriverException e) {77			logger.error("Unable dismiss the alert \n " + e.getMessage());78			throw new WebDriverException("Unable dismiss the alert \n " + e);79		}80		if (waitForElement != null && waitForElement.length > 0) {81			setWebDriverWait(waitForElement[0]);82		}83	}8485	public String getAlertText(WebElement... waitForElement) {86		String alertText = null;87		try {88			/*driver.switchTo().defaultContent();*/89			if (isAlertPresent()) {90				Alert alert = driver.switchTo().alert();91				logger.info("Switching to alert");92				alertText = alert.getText();93			}94			95		} catch (WebDriverException e) {96			logger.error("Unable get the text from an alert \n " + e.getMessage());97			throw new WebDriverException("Unable get the text from an alert \n " + e);98		}99		if (waitForElement != null && waitForElement.length > 0) {100			setWebDriverWait(waitForElement[0]);101		}102		return alertText;103	}104105	public void loginWithoutPopup(String urlWithoutHTTPS, String userName, String password, WebElement... waitForElement) {106		try {107			String newURL = "https://" + userName + ":" + password + "@" + urlWithoutHTTPS;108			driver.get(newURL);109		} catch (WebDriverException e) {110			logger.error("Unable top login to the application with windows authentication.\n" + e.getMessage());111			throw new WebDriverException("Unable top login to the application with windows authentication.\n" + e);112		}113		if (waitForElement != null && waitForElement.length > 0) {114			setWebDriverWait(waitForElement[0]);115		}116	}117}
...getMessage
Using AI Code Generation
1package org.seleniumhq.selenium;2import org.openqa.selenium.WebDriverException;3public class WebDriverExceptionDemo {4    public static void main(String[] args) {5        WebDriverException e = new WebDriverException("message");6        System.out.println(e.getMessage());7        System.out.println(e.getAdditionalInformation());8        System.out.println(e.getSupportUrl());9        System.out.println(e.getSystemInformation());10        System.out.println(e.getBuildInformation());11        System.out.println(e.getScreenShot());12        System.out.println(e.getStackTrace());LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
