Selenium 简明教程

Selenium - Exception Handling

可以使用 Selenium Webdriver 执行异常处理。在开发测试时,我们应该确保即使出现错误,脚本也可以继续执行。异常类似于在触发执行测试时遇到的错误。

Exception Handling can be performed using the Selenium Webdriver. While developing our tests, we should ensure that the scripts can continue their execution even if there is an error. An exception is similar to an error encountered while our tests are triggered for execution.

如果由于找不到元素或预期结果与实际结果不符或由于任何其他原因导致异常,我们的代码应该生成异常并以合乎逻辑的方式结束测试,而不是突然终止脚本。异常有两种类型:

If an exception occurs due to an element not found or if the expected result doesn’t match with actuals or for any other reasons, our code should generate an exception and end the test in a logical way rather than terminating the script abruptly. Exceptions are of two types −

  1. Checked Exceptions − These exceptions can be taken care of while developing the code prior compilation of it.

  2. Unchecked Exceptions − These exceptions can be detected only at runtime and are more difficult to handle than the checked exceptions.

识别和解决未检查异常的方法被称为异常处理。Selenium 中提供的一些异常包括:

The method of identifying and solving the unchecked exceptions is known as exception handling. Some of the exceptions available in Selenium are −

  1. ElementNotVisibleException − This exception is generated when an element is available in DOM, but it is invisible. Hence no actions can be done on it.

  2. ElementNotInteractableException − This exception is generated when an element is available in DOM. However, when performing action on it, another element is getting affected.

  3. ElementClickInterceptedException − This exception is generated when an element click command could not be achieved. This is because the element which is receiving the event is hiding the element that requested the click operation.

  4. ElementNotSelectableException − This exception is generated when an element which is unselectable is made an attempt to select

  5. InsecureCertificateException − This exception is generated when a navigation is responsible to hit a certificate warning. This resulted in creating an expired and incorrect certificate of TLS.

  6. ErrorInResponseException − This exception is generated due to an error on the server side.

  7. ImeActivationFailedException − This exception is generated due to a failed activation of the IME engine.

  8. ImeNotAvailableException − This exception is generated if IME support is unavailable.

  9. InvalidElementStateException − This exception is generated if a command remains incomplete as the element state is not valid

  10. InvalidArgumentException − This exception is generated if a command argument is not valid.

  11. InvalidCoordinatesException − This exception is generated if the coordinates for operations are not valid.

  12. InvalidCookieDomainException − This exception is generated for adding a cookie under a different domain and not in the present URL.

  13. InvalidSwitchToTargetException − This exception is generated when the target window or frame to be switched is nonexistent.

  14. InvalidSelectorException − This exception is generated if the selector to identify an element fails to get a WebElement.

  15. MoveTargetOutOfBoundsException − This exception is generated when the target to the method ActionsChains move() is not valid.

  16. InvalidSessionIdException − This exception is generated if the provided session id is either inactive or nonexistent and is not a part of the active sessions.

  17. NoSuchFrameException − This exception is generated when the target frame to be switched is nonexistent.

  18. NoAlertPresentException − This exception is generated when the target alert to be switched is nonexistent.

  19. NoSuchCookieException − This exception is generated when there is no matching cookie amongst the cookies of the present browsing active content.

  20. NoSuchAttributeException − This exception is generated when an element attribute is missing.

  21. UnableToSetCookieException − This exception is generated when a driver is not able to set a cookie.

  22. NoSuchWindowException − This exception is generated when the target window to be switched is nonexistent.

  23. TimeoutException − This exception is generated when a command execution does not complete in a time range.

  24. StaleElementReferenceException − This exception is generated when an element reference is currently stale.

  25. UnexpectedTagNameException − This exception is generated when an assisting class did not find the proper web element.

  26. UnexpectedAlertPresentException − This exception is generated when an unexpected alert has come up.

  27. NoSuchElementException − This exception is a child class of NotFoundException class. It is generally thrown by the findElement() method, when an element cannot be identified in DOM.

  28. SessionNotFoundException − This exception is thrown when the driver makes an attempt to do something on the web page while the browser session is terminated or closed.

  29. WebDriverException − This exception is thrown when the driver makes an attempt to work straight away just after closure of the driver session.

让我们讨论一些处理异常的方法 −

Let us discuss some of the ways to handle exceptions −

Use try-catch block

try 表示块的开头,catch 放在 try 块后面,用于解决异常。

The try indicates the beginning of the block and catch is placed just after the try block to resolve the exception.

Syntax

try {

   //Perform Action
} catch(Exception e1) {

   //Catch block 1
}

Use try and multiple catch blocks

某些代码段可能会产生多个异常。每个 catch 块用于处理单一类型的异常。

Some pieces of code can produce multiple exceptions. Each catch block is used to handle a single type of exception.

Syntax

try {

   //Perform Action
} catch(Exception e1) {

   //Catch block 1
} catch(Exception e2) {

   //Catch block 2
}

Use throw and throws

throw 关键字用于生成自定义异常。如果不处理就抛出异常,则方法签名中应提及 throws 关键字。

The throw keyword is used to generate a customized exception. If an exception is thrown without handling it, we should have the throws keyword mentioned in the method signature.

Syntax

public static void errorHandling() throws Exception
try {

   //Perform Action
} catch(Exception e) {

   throw(e);
}

Use try-catch-finally block

try 表示块的开头,catch 放在 try 块后面,用于解决异常。无论脚本是否抛出异常,finally 代码块都会执行。

The try indicates the beginning of the block and catch is placed just after the try block to resolve the exception. The finally block of code executes regardless of whether the script had thrown an exception or NOT.

Syntax

try {

   //Perform Action
} catch(Exception e1) {

   //Catch block 1
} finally {

   //The finally block always executes.
}
  1. printStackTrace() − This provides information about the exception, stack trace, and other critical information about the execution.

  2. toString() − This describes the exception name and its purpose.

  3. getMessage() − This describes the exception.

让我们举个例子,其中在程序中遇到错误,并且由于代码中没有异常处理,导致执行中途停止。

Let us take an example where an error got encountered in the program and execution was halted in between since there was no exception handling in the code.

Example

ExceptionsEncountered.java 类文件中的代码实现。

Code Implementation on ExceptionsEncountered.java class file.

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ExceptionsEncountered {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // launch an application and open a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/auto-complete.php");

      // identify element with incorrect xpath value
      WebElement l = driver.findElement(By.xpath("//*[@id='tag']"));

      // enter text
      l.sendKeys("Selenium");

      // Quitting browser
      driver.quit();
   }
}

Output

Exception in thread "main"
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
   {"method":"xpath","selector":"//*[@id='tag']"}
(Session info: chrome=121.0.6167.160)
For documentation on this error, please visit:
   https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

Process finished with exit code 1

在上述示例中,我们收到了 NoSuchElementException。由于在上述实现中未应用异常处理,因此在遇到错误后立即停止了执行。

In the above example, we have received the NoSuchElementException. As exception handling was not applied in the above implementation, the execution halted immediately after the error was encountered.

最后,收到了消息 Process finished with exit code 1 ,表示代码执行失败。

Finally, the message Process finished with exit code 1 was received, signifying unsuccessful execution of the code.

让我们看看如何使用 try-catch 和 finally 块在上述测试中添加异常处理。

Let us see how to add the exception handling in the above test using the try-catch and finally block.

Example

ExceptionHandlingEncountered.java 类文件中的代码实现。

Code Implementation on ExceptionHandlingEncountered.java class file.

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ExceptionHandlingEncountered {
   public static void main(String[] args) {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // launch an application and open a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/auto-complete.php");

      //try-catch finally block
      try {

         // identify element with incorrect xpath value
         WebElement l = driver.findElement(By.xpath("//*[@id='tag']"));

         // enter text
         l.sendKeys("Selenium");

      } catch (NoSuchElementException e){
         System.out.println("Catch block executed after try block");
      }

      // finally block
      finally {
         System.out.println("finally block executed after try - catch block");
      }

      // Quitting browser
      driver.quit();
   }
}

Output

Catch block executed after try block
finally block executed after try - catch block

Process finished with exit code 0

在本教程中,我们讨论了如何使用 Selenium Webdriver 执行异常处理。

In this tutorial, we had discussed how to perform exception handling using Selenium Webdriver.