处理由Selenium引发的错误

时间:2017-02-24 18:34:23

标签: java selenium error-handling

假设我有一个对象:

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

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

public class SOClass {
    private WebDriver driver;
    private List<String> dataString;


    public SOClass(WebDriver driver) throws ArrayIndexOutOfBoundsException {
        this.driver = driver;
        prepData();
    }

    private void prepData() throws ArrayIndexOutOfBoundsException {

        List<WebElement> data = this.driver.findElements(By.className("a-export-table"));
        if(data.isEmpty()) {
            throw new ArrayIndexOutOfBoundsException("There was no data in the table to export");
        }
        for(WebElement w : data) {
            this.dataString.add(w.getText());
        }
    }

    public void export(String path) throws IOException {
        FileWriter fw = new FileWriter(path);
        boolean isFirst = false;
        for(String s : this.dataString) {
            if(isFirst) {
                fw.append(s);
            } else {
                fw.append("," + s);
            }
        }
        fw.flush();
        fw.close();

    }
}

和主要:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class SOMain {
    private static final String COMPUTER_NAME = System.getProperty("user.name");
    private static final String CHROME_PATH =
            "C:/Users/" + COMPUTER_NAME + "/selenium/chromedriver.exe";

    private static final String OUT_PATH =  "C:/Users/" + COMPUTER_NAME + "/output/export.csv";

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", CHROME_PATH);
        ChromeOptions options = new ChromeOptions();
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        WebDriver driver = new RemoteWebDriver(capabilities);
        driver.get("www.someurlexample.com");
        try {
            SOClass so = new SOClass(driver);
            so.export(OUT_PATH);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

现在,除非出现任何编译问题(我将此作为示例),我的代码将捕获SOClass定义为抛出的任何异常。但是,我想知道页面上是否存在该表,而Selenium会抛出NoSuchElementException,我的SOMain会因为

而自动捕获此异常
 } catch(Exception e) {
 }

阻止,或者因为没有指定对象抛出此错误,SOMain将不会处理此错误并中断?

1 个答案:

答案 0 :(得分:1)

您的catch将处理从Exception类继承的所有异常(显然出现在try中),这意味着包括NoSuchElementException,如您所见{ {3}}它的层次结构。

但是,您需要区分 Checked Exceptions Unchecked Exceptions 或Runtime Exceptions。如您所见NoSuchElementException扩展java.lang.RuntimeException,这意味着它未经检查,因此编译器不需要您处理它。但请记住,此运行时异常会扩展java.lang.Exception,因此catch会在运行时发现它{。}}。