Why dosnt my method catch my 'Timeout Exception' and print to console? - java

Why dosnt my method catch my 'Timeout Exception' and print to console?
public void clickDrivingExperienceButton() throws Exception {
boolean test = this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();
try {
if (test == true) {
link_DrivingExperiences.click();
}
System.out.println("Successfully clicked on the driving experience button, using locator: " + "<" + link_DrivingExperiences.toString() + ">");
}catch (TimeoutException e) {
System.out.println("WHY DONT I PRINT ANYTHING??????" + e.getMessage());
}catch (Exception e) {
System.out.println("Unable to click on the Driving Experience Button, Exception: " + e.getMessage());
} finally {
// final code here
}
}

Most likely timeout exception throws out of this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();, and your try-catch block doesn't enclose that line

Put this.wait.until inside try block.
Exception message already tells that the exception occurred when it was waiting for the element to be clickable.
public void clickDrivingExperienceButton() throws Exception {
try {
boolean test = this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).isEnabled();
if (test == true) {
link_DrivingExperiences.click();
}
System.out.println("Successfully clicked on the driving experience button, using locator: " + "<" + link_DrivingExperiences.toString() + ">");
}catch (TimeoutException e) {
System.out.println("WHY DONT I PRINT ANYTHING??????" + e.getMessage());
}catch (Exception e) {
System.out.println("Unable to click on the Driving Experience Button, Exception: " + e.getMessage());
} finally {
// final code here
}
}

Your try-catch isn't catching the exception because the exception comes from the 2nd line (wait.until) and that's not inside the try-catch.
You've got many of the same issues that I addressed in your other question, https://stackoverflow.com/a/42120129/2386774, that I would suggest that you fix up in this code also.
It should basically be the below
public void clickDrivingExperienceButton() throws Exception
{
this.wait.until(ExpectedConditions.elementToBeClickable(link_DrivingExperiences)).click();
}
You shouldn't really need to log as much as you are logging. If the element is successfully clicked, the script will progress. Logging that is just going to clog up your logs, IMO. There's also no point in logging an exception because it's going to be dumped to the logs anyway. Generally, you want your script to stop when an exception is thrown unless proceeding won't be affected by it. That largely depends on your scenario so you will have to make the final decision on whether to proceed or not which will determine how you handle thrown exceptions.

Related

Best practice - Generic webdriverWait till loading popup exist, if error appears fail the test

My problem is I have customWaitMethods such as:
public void waitForLoading(WebElement loadingElement, WebElement errorElement) {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id(loadingElement.toString())));
if (errorElement.isDisplayed()) {
throw new TestException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after default time out");
} catch (TestException e) {
System.out.println("Unexpected error occurred, environment error");
e.printStackTrace();
}
}
I need some generic customWait methods. I do a search, but several cases need to be handled. Error msg appear -> fail the test. wait for the loading content, and it disappeared, -> check the search result.
How can I extend this code if I would like to check continuously some error_message element appears as well and in this case I would throw an exception? So independently I can handle the timeout exception and the other, error msg?
This sript is failing because of the IF. ErrorElement does not appear on the page, ---> nosuchelementException
You can catch different Exceptions as you see fit. In your case, you want to catch the TimeoutException to handle time outs. Then catch a different type of exception to handle the error message:
public void waitForLoading() {
long timeOut = Long.parseLong(...);
try {
WebDriverWait wait = new WebDriverWait(...);
wait.until(ExpectedConditions.invisibilityOfElementLocated(...));
if (<error-message-appears>) {
throw new CustomErrorMessageAppearedException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after...");
} catch (CustomErrorMessageAppearedException e) {
// handle error message
}
}
The easiest approach I see is:
public void waitForLoading() {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
if (!wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("wait_element")));)
{
throw new NoSuchElementException();
}
} catch (TimeOutException e) {
System.out.println("Timed out after " + timeOut + "seconds waiting for loading the results.");
}
}

A Robust Try Catch Method to use in WebDriver?

A Robust Try Catch Method to use in WebDriver?
Can someone advice from there experiece whether the following method looks correct in the likely scenario where searching for an element gets timed out or the incorrect locator has been used?
The timeout Exception dosnt seem to be printing my System.out.println after i set the wait to 2seconds and change the locator with the wrong xpath
My Code:
public void clickSupercarsLink() throws Exception {
try {
this.wait.until(ExpectedConditions.elementToBeClickable(link_Supercars)).click();
} catch (TimeoutException e) {
System.out.println("UNABLE TO FIND ELEMENT : Timeout");
} catch (Exception e) {
System.out.println("UNABLE TO FIND ELEMENT : Exception");
throw (e);
}
}
New Code:
public void clickSupercarsLink() throws Exception {
try {
this.wait.until(ExpectedConditions.elementToBeClickable(link_Supercars)).click();
} catch (TimeoutException e) {
System.out.println("Timed out attempting to click on element: <" + link_Supercars.toString() + ">");
} catch (Exception e) {
System.out.println("Unable to click on element: " + "<" + link_Supercars.toString() + ">");
}
}
#Phil I would want you to throw that exception and handle it at high level. In current scenario, if there is a critical exception, your test will method calling your method clickSupercarsLink will not know that there was an exception.
Any way you are throwing exception, why do you have to catch it and do nothing with it then just printing!! This is not why you throw exception right?
public void clickSupercarsLink() throws Exception {
this.wait.until(ExpectedConditions.elementToBeClickable(link_Supercars)).click();
}

How to avoid throw clause in finally block

I am using SonarQube for code quality. I got one issue related to exception handling, which says remove throw clause from finally block.
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}
}
Based on my understanding above code looks good. If I remove throw clause and suppress exception in finally then caller of this method will not be able to know server's status. I am not sure how we can achieve same functionality without having throw clause.
Your best shot is to use the Automatic Resource Management feature of Java, available since Java 7. If that is for some reason not available to you, then the next best thing is to replicate what that syntactic sugar expands into:
public static void runWithoutMasking() throws MyException {
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
autoClose.work();
} catch (MyException e) {
myException = e;
throw e;
} finally {
if (myException != null) {
try {
autoClose.close();
} catch (Throwable t) {
myException.addSuppressed(t);
}
} else {
autoClose.close();
}
}
}
Things to note:
your code swallows the original exception from the try block in case closing the resource fails. The original exception is surely more important for diagnostic;
in the ARM idiom above, closing the resource is done differently depending on whether there already was an exception in the try-block. If try completed normally, then the resource is closed outside any try-catch block, naturally propagating any exception.
Generally, methods in the finally block are 'cleanup' codes (Closing the Connection, etc) which the user does not necessarily need to know.
What I do for these exceptions is to absorb the exception, but log the details.
finally{
try{
connection.close();
}catch(SQLException e){
// do nothing and just log the error
LOG.error("Something happened while closing connection. Cause: " + e.getMessage());
}
}
You're getting a warning because this code could potentially throw an exception while dealing with a thrown exception. You can use the try with resource syntax to close the resource automatically. Read more here.
In the case that the "request failed : " exception is thrown and you fail to close the httpclient, the second exception is the one that would bubble up.
I am not sure how we can achieve same functionality without having
throw clause.
You could nest the two try blocks differently to achieve the same result:
HttpClient httpClient = null; // initialize
try {
try {
// do something with httpClient
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
httpClient.close();
}
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}

Usage of "(!Oracle.acquireLockNoWait)"

private void acquireEtlLock() throws StepwiseException {
try {
if (!Oracle.acquireLockNoWait(this.context.getConnection(), getProcessLockName())) {
throw new StepwiseException("Another session is in progress for process: "
+ this.context.getSession().getProcessName());
}
this.isLockAcquired = true;
} catch (SQLException e) {
throw new StepwiseException("Error acquiring session lock for process: "
+ this.context.getSession().getProcessName(), e);
}
}
I would like to know the exact functionality of "!Oracle.acquireLockNoWait", actually this is a method to call a cron job, but for some reason i dont find the job to be running. So just wanted to check if this code could cause a block or a deadlock.
I am receiving the error "Another session is in progress for process: ", what could be the possible reasons for this?

Can't catch a FileNotFoundException when using DOMConfigurator

I have the following code:
try {
DOMConfigurator.configure(url+log4j.xml);
} catch(Exception e) {
e.printStackTrace();
}
And I would expect a FileNotFoundException if the log4j.xml doesn't exist, and then the catch-block would be executed.
But I don't see an exception when the file doesn't exist, why is that?
If you look at the source of DOMConfigurator.doConfigure it looks like it catches Exception and then just logs the error rather than rethrowing it. Therefore the FileNotFoundException will not make it back to your calling code.
try {
...
} catch (Exception e) {
if (e instanceof InterruptedException || e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
// I know this is miserable...
LogLog.error("Could not parse "+ action.toString() + ".", e);
}
To work around this you could preemptively check if the file exists yourself.
Try catching a Throwable instead of an Exception and do a print stack trace. That way you can catch any errors or exceptions and change your code accordingly.
In case you want to disable those messages from log4j, you can set log4j in quiet mode:
LogLog.setQuietMode(true);

Categories