javaselenium-webdriverreflectionselenium-chromedriverinvocationtargetexception

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


I am opening the Chromebrowser, and getting the exeption "InvocationTargetException". The code was running properly few days ago. Here is my code

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

At the line "driver=new ChromeDriver();" I am getting the "InvocationTargetException" Exception


Solution

  • 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() method, as well as the aforementioned "legacy method."

    Solution

    The best approach would be to unwrap the cause within the InvocationTargetException to get the the original exception.

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

    Best Practice

    As per the best practices follow the below guidelines: