So, after understanding 'What is an Exception and the different types of Exceptions in Selenium WebDriver', you are now ready to understand ElementNotVisibleException in a detailed and practical way.
ElementNotVisibleException occurs when the locators (i.e. id / xpath / css selectors etc) we have provided in the Selenium Program code is trying to find the web element which is in hidden from displaying on the page. For example, there is no button displayed on the web page and if there is HTML code related to the button, then on trying to find the button using locators of the button by executing the Selenium Code, we get ElementNotVisibleException .
Practical Example for ElementNotVisibleException :
1. Open Firefox browser and browse http://www.omayo.blogspot.com as shown below:
2. Right click on the Page and select 'View Page Source' option as shown below:
3. Find out the HTML code for any hidden button on the page shown in above image from the Page Source as shown below:
Note: Hidden button is the button which is not displayed on the web page User Interface.
4. Create an XPath locator, which can locate this hidden button as shown below:
5. Write Selenium Code to click on the hidden button, using its XPath locator as shown below and execute it:
6. Observe that ElementNotVisibleException has occurred and displayed in the Eclipse IDE console as shown below:
7. Also observe that, all the statements after the exception occurred statement wont be executed. i.e. The lines in the below image wont be executed:
Handling ElementNotVisibleException :
1. If you want those statements to be executed, even after the Exception has occurred in the before statement, we need to handle the Exception using Exceptional Handling mechanism:
i.e. We have to use try .. catch blocks to handle the exception and also 'ElementNotVisibleException' WebDriver Exception Class needs to be used in the catch block as shown in the below code:
2. Hover the mouse over the 'ElementNotVisibleException' error in the above image and select 'import ElementNotVisibleException org.openqa.selenium ' option from the suggested resolutions as shown below:
3. Observe that the error gets resolved as shown below and execute the code:
4. Observe that the Exception got handled successfully and statements after the Exception got executed as a result of handling the exception. The below screen-shot is the proof that the ElementNotVisibleException is handled using Exception handling mechanism:
Hence on trying to locate the hidden button (which is not visible on the page and has HTML code available), we get ElementNotVisibleException WebDriver Exception. In order to handle this, we have to use ElementNotVisibleException WebDriver Class in the catch block.