【问题标题】:Why does not the try/catch in java work on my case? [closed]为什么 java 中的 try/catch 不适用于我的案例? [关闭]
【发布时间】:2021-06-25 08:48:38
【问题描述】:

我在 java selenium 上写了一个 try/catch 块,但我不明白为什么它不起作用。它应该检查网页上的 web 元素,如果没有找到它应该抛出 NoSuchElementException 并转到 catch 块。真正发生的是找不到元素并且执行不会继续 catch 块,它未通过测试(Selenium WebTest)并完全停止执行,使我的测试失败。我还在主要方法中包含“抛出 NoSuchElementException”。这里有一些代码供参考。问题可能是什么?如何编写防故障代码?

 try {
// this is the web element to be found by xpath,sometimes it is on the webpage,sometimes not

can = driver.findElement(By.xpath("//*[@id=\"revealGameAnimation\"]/canvas"));
}

catch(NoSuchElementException e)
{

// some code here

}

【问题讨论】:

  • 您可以捕获异常 e,然后打印出异常的类,以找出您的捕获不起作用的原因 e.getClass()
  • 请始终在问题中显示完整的错误。从comment you wrote 到答案,您得到的错误似乎是org.openqa.selenium.NoSuchElementException,我敢打赌您错误地导入了java.util.NoSuchElementException,这就是它没有捕获实际抛出的异常的原因。
  • 感谢您的详细解释。有人可以正确地告诉我如何以正确的方式在问题中包含源代码吗?我是 StackOverflow 的新手,我还不明白它是如何使用代码添加问题等的。

标签: java selenium try-catch


【解决方案1】:

您的代码不起作用,因为 Selenium 在这种情况下会抛出 ElementNotFoundException 异常。

【讨论】:

  • 它抛出“NoSuchElementException”。仔细阅读我的问题。运行测试后,我在这里有错误日志。检查这里的错误“org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="revealGameAnimation"]/canvas" }”。
  • @Erli 你确定你的代码导入了org.openqa.selenium.NoSuchElementException,而不是例如java.util.NoSuchElementException?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2013-12-12
  • 2012-05-14
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多