在 driver=new ChromeDriver(); 行获取 "InvocationTargetException" 异常;

Getting the "InvocationTargetException" exception on the line driver=new ChromeDriver();

我正在打开 Chrome 浏览器,并获得了例外 "InvocationTargetException"。几天前代码是运行。这是我的代码

System.setProperty("webdriver.chrome.driver","D:\Automation\chromedriver_win32\chromedriver.exe");
driver=new ChromeDriver();

"driver=new ChromeDriver();" 行,我收到 "InvocationTargetException" 异常

InvocationTargetException

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. It is an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException. The "target exception" that is provided at construction time and accessed via the getTargetException() method is now known as the cause, and may be accessed via the Throwable.getCause()方法,以及前面提到的"legacy method."

解决方案

最好的方法是 解包 InvocationTargetException 中的原因以获得原始异常。

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();
}

最佳实践

按照最佳做法遵循以下准则: