try {
WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myDynamicElement")));
} catch (TimeOutException toe) {
2 Answers
TimeOutException
exception is thrown when Selenium fails locating on the page element matching the passed locator. myDynamicElement
id in your case.
This may be caused by one of the following:
1)
You are using a wrong locator.
2)
The element is inside an iframe.
3)
You have opened a new tab / window on your browser but did not switch the driver to the new opened tab.
Etc.

- 32,350
- 22
- 54
- 79
Java Exceptions
When executing Java programs different errors can occur, e.g. coding errors made by the programmer, errors due to wrong input or any other unforeseeable things. When any of these error occurs, Java will throw an exception.
Java Try-Catch{}
The try and catch keywords come in pairs.
try: The try statement allows you to define a block of code to be tested for errors while it is being executed.
catch: The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
visibilityOfElementLocated()
visibilityOfElementLocated() is the expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0 which returns the WebElement once it is located and visible else raises TimeOutException.
This usecase
I don't see any such syntactical error in your code block:
try {
WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myDynamicElement")));
} catch (TimeOutException toe) {
System.out.println("WebElement wasn't found");
}
However there can be numerous reasons for the WebElement not being found and some of them are as follows:
- The Locator Strategy you have adopted doesn't identifies any element in the HTML DOM.
- The Locator Strategy you have adopted is unable to identify the element as it is not within the browser's Viewport.
- The Locator Strategy you have adopted identifies the element but is invisible due to presence of the attribute style="display: none;".
- The Locator Strategy you have adopted doesn't uniquely identifies the desired element in the HTML DOM and currently finds some other hidden / invisible element.
- The WebElement you are trying to locate is within an
<iframe>
tag. - The WebDriver instance is looking out for the WebElement even before the element is present/visibile within the HTML DOM.
Solution
Each of the above mentioned cases can be addressed using different approaches. You can find a couple of detailed discussion in:

- 183,867
- 41
- 278
- 352