我正在打开 Chrome 浏览器,并收到异常“InitationTargetException”
。几天前代码运行正常。这是我的代码
System.setProperty("webdriver.chrome.driver","D:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
在 "driver=new ChromeDriver();"
行,我收到 "InitationTargetException"
异常
最佳答案
调用目标异常
InvocationTargetException是一个已检查的异常,它包装了由调用的方法或构造函数抛出的异常。通过反射调用方法,这是一个额外的抽象级别。反射层将所有异常包装在 InitationTargetException
中。在构造时提供并通过 getTargetException()
访问的“目标异常”方法现在被称为原因,可以通过 Throwable.getCause()
访问方法,以及前面提到的“遗留方法”。
解决方案
最好的方法是解开InitationTargetException
中的原因以获取原始异常。
try {
System.setProperty("webdriver.chrome.driver","D:\\Automation\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
} catch (InvocationTargetException e) {
// the real cause
e.getCause().printStackTrace();
} catch (Exception e) {
// generic exception handling
e.printStackTrace();
}
<小时/>
最佳实践
根据最佳实践,请遵循以下准则:
- 将ChromeDriver升级到当前的ChromeDriver v74.0.3729.6级别。
- 将 Chrome 版本保持在 Chrome v74 级别。 (as per ChromeDriver v74.0.3729.6 release notes)
- 以非root用户身份执行
@Test
。 - 始终在
tearDown(){}
方法中调用driver.quit()
来关闭和销毁 WebDriver 和 Web Client 优雅地实例化。
关于java - 在 driver=new ChromeDriver(); 行上获取 "InvocationTargetException"异常;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55846217/