【问题标题】:Thread.sleep won't work unless it is wrapped in a try catch block in Selenium [duplicate]除非将 Thread.sleep 包装在 Selenium 中的 try catch 块中,否则 Thread.sleep 将不起作用 [重复]
【发布时间】:2019-08-09 19:43:06
【问题描述】:

我正在编写硒代码。

除非我将 Thread.Sleep 放在 try catch 块中,否则它将无法工作。它实际上会引发编译时错误。

为什么会这样?

	public void test() {
		
		System.out.println("in the test method");
		achromeDriver.get(abaseUrl);
		
		try {
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		WebElement benzRadioBtn = achromeDriver.findElement(By.id("benzradio"));
		benzRadioBtn.click();
		
		WebElement benzCheckBox = achromeDriver.findElement(By.id("benzcheck"));
		benzCheckBox.click();
		
		System.out.println("Is ben radio button selected ? "+  benzRadioBtn.isSelected());
		
	}

【问题讨论】:

    标签: java selenium selenium-chromedriver


    【解决方案1】:

    Thread.sleep() 方法会引发 InterruptedException。这个异常是否真的会被抛出取决于你的java代码执行过程中发生了什么,这个方法只是让你知道它可能发生,并且你应该以某种方式处理它。

    处理异常的一种方法是将其放在 try catch 块中,因此如果抛出异常,程序仍将继续,并且 catch 块中的代码将执行。

    如果您真的不想要 try catch 块(不知道为什么不想要),您可以在方法顶部添加一个 throws 声明,如下所示:

        public void test() throws InterruptedException {
    

    我会阅读更多有关 java 异常及其工作原理的信息

    https://stackify.com/specify-handle-exceptions-java/

    https://www.geeksforgeeks.org/exceptions-in-java/

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多