Failure of "try" not going to "catch" block - java

This code is written to get the error reported in console if WebElement is not found on page. It fails on try block but doesn't go to catch.
I have tried different tweaks and tricks but its not working, please share what am I missing:
Code:
public class GetElement extends TestBase{
WebDriverWait wdw = new WebDriverWait(driver, 10);
public WebElement getElement(WebElement element) {
try {
System.out.println("\n" + "==============" + "\n"
+ "inside try of gE" + "\n" + "===================");
return wdw.until(ExpectedConditions.elementToBeClickable(element));
} catch (NoSuchElementException | TimeoutException ex) {
System.out.println("\n" + "==============" + "\n"
+ element.getText()
+ " Element not or wasnt clickable found on page" + "\n"
+ driver.getCurrentUrl() + "\n" + "===================");
}
System.out.println("\n" + "==============" + "\n"
+ "Element will be returned as null"+ "\n" + "===================");
return null;
}
}
here TestBase initializes the WebDriver
Exception that I get often is (often, because I was also getting time out but then I increased time):
org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 137 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'

Several possobilities.
The exception thrown is org.openqa.selenium.NoSuchElementException. Because NoSuchElementException is a fairly common name, I suspect in your code the NoSuchElementException isn't from your org.openqa.selenium package.
The exception is thrown from outside of the try block at all.
If you still cannot work out where it's from, add a catch block to catch all Exception after and see if the exception is correctly triggered in your try block.

What Alex said is right, your catch block catches java.util.NoSuchElementException - from , but you must be actually getting a
org.openqa.selenium.NoSuchElementException.
Try this catch block:
catch(org.openqa.selenium.NoSuchElementException e| TimeoutException ex){

Related

instead of catching Java MalformedURLException, build failing

New to Java, so please bear with me:
(and please note that this qestion is about Java Exceptions, not Jsoup)
when using Jsoup in order to get Html page: (Jsoup.connect(current_url._name).get();) , I tried to catch all possible 5 exceptions according to the Jsoup documentation: here
the program works fine with good URLs, but when I intentionally misspelled 1 URL to check what happens, I was surprised to see that the exception wasn't catch, instead the program start running, then the "Build failed"?
when only building the program there is no failure, so I think it isn't really
build issue.
here is the code:
// load html and check them:
for(URL current_url : URLs)
{
// no keyword - all getting 'yes'
if(keywords.isEmpty())
{
current_url._stat = URL_stat.YES;
}
// there are keywords - get pages and check them
else
{
Document html_doc;
// try to get document and catch all errors
try
{
html_doc = Jsoup.connect(current_url._name).get();
}
catch(MalformedURLException e)
{
System.out.println("the request " + current_url._name +
" URL is malformed");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(HttpStatusException e)
{
System.out.println("page " + current_url._name + " response"
+ " is not ok");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(UnsupportedMimeTypeException e)
{
System.out.println("page " + current_url._name+ " mime type"
+ " is not supported");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(SocketTimeoutException e)
{
System.out.println("connection to " + current_url._name +
" times out");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(IOException e)
{
System.out.println("an error occurred while getting page "
+ current_url._name);
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
// check if document has paragraphs, if not mark - no
}
}
and the output:
Exception in thread "main" java.lang.IllegalArgumentException: Malformed URL: ttp://cooking.nytimes.com/topics/what-to-cook-this-week
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:76)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at ex2.Ex2.main(Ex2.java:123)
Caused by: java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:74)
... 3 more
C:\Users\Administrator\AppData\Local\NetBeans\Cache\8.2\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
Thanks,
It is because the first exception being thrown is an IllegalArgumentException, which you have not defined in any of your catch clauses, thus preventing you from getting your custom error messages in any other catch blocks.

AssertTrue in try/catch

Please what exactly am i doing wrong.
I have checked and checked but all to no avail.
I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.
The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.
I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.
Code below including print out message in console.
public boolean verifyTextPresent(String value) throws Exception {
Thread.sleep(5000);
try{
boolean txtFound = driver.getPageSource().contains(value);
log.log(value + " : text Found, .......continue");
return txtFound;
}catch(Exception e)
{
log.log(value + " :NOT Found, check element again ot Contact developer.");
return false;
}
}
public static void verifySignOutBtn() throws Exception
{
log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");
callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
Thread.sleep(2000);
log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
Thread.sleep(4000);
log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");
try{
Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");
log.log("User Successfully Signed Out.......");
log.log("Test Passed!...");
//callMethod.close();
}
catch(Throwable e)
{
log.log("User NOT Successfully Signed Out.... Contact developer.");
log.log("Test Failed!...");
//callMethod.close();
}
callMethod.close();
}
}
Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...
The confusing part is that why is it printing out the catch block instead of the next line in the try block?
Shouldn't it be the other way around?
Assert.assertTrue("Message if it is false", callMethod.verifyTextPresent("SIGN IN"));
The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this
log.log(value + " : text Found, .......continue");
for example with this line
log.log(value + " : text Found, ......." + txtFound);
or just print the stacktrace in catch block.

log the exception in spring using aspectJ?

Please don't hesitate to edit the question or to ask more details about the questin.
I know I can log the ArithmeticException of the below method using the aspectJ as,
public void afterThrowingAspect(){
System.out.println("This is afterThrowingAspect() !");
int i=2/0;
System.out.println("i value : "+i);
}
The AspectJ class has,
#AfterThrowing(pointcut = "execution(* com.pointel.aop.test1.AopTest.afterThrowingAspect(..))",throwing= "error")
public void logAfterError(JoinPoint joinPoint,Throwable error) {
System.out.println("Hi jacked Method name : " + joinPoint.getSignature().getName());
log.info("Method name : " + joinPoint.getSignature().getName());
log.info("Error report is : " + error);
}
Normally I can handle exception using the TRY and CATCH block and log the errors in the every CATCH block as ,
public void someMehtod(){
try{
int i=2/0;
System.out.println("i value : "+i);
}catch{ArithmeticException err){
log.info("The exception you got is : " + err);
}
}
But I don't like to do the logging like with every single catch block individually in all the java classes of my project like ,
log.info("The exception you got is : " + err);
I would like to do the logging inside CATCH block in my application using the aspectJ class.
Hope you are all understand my question.Thanks.
Its possible to simply remove the try/catch from your code and simply log the exception in your aspect.
public void someMehtod(){
int i=2/0;
System.out.println("i value : "+i);
}
Because you don't re-throw the exception in the aspect then it won't bubble up. Although this is possible I strongly advise you to think more about what you are trying to do here. Why do you need to log the fact that an exception has been thrown? Exceptions aren't necessarily only for errors but can occur in normal code journeys. Simply logging only the exception name is unlikely to help you debug the problem. Therefore, you will probably want a bespoke log message for each catch block. If you do find repetition you could create a method to log out the result.
Hope this helps,
Mark

NoSuchElementException after switching frames

UPDATE:
I think I saw the error, I configure again my Selenium IDE and recreate the test, and when i open in Eclipse i see this comments in code:
public void testEcsf3() throws Exception {
driver.get(baseUrl + "/something.com");
WebElement frame = driver.findElement(By.name("body"));
driver.switchTo().frame(frame);
//...
//code for navigate to the target page
//...
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | name=body | ]]
//Target page - another frame with name 'body'
driver.findElement(By.xpath("//tr[28]/td[2]/a/font")).click();// <-- target element in target page
//...
//code for navigate to the target page
//...
}
The problem is that the flow between pages have more of one frame with name 'body'(i can't change that), how i can make this work?
Thanks.
--
I'm trying to use a Selenium testcase(Ok in browser) using JUnit in Eclipse.
When I try to run the testcase I receive this error:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"user"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Note: the link mentioned in the error has no content!
This is the point of error:
driver.get(baseUrl + "/something.com");
driver.findElement(By.name("user")).sendKeys("aaa"); //<--
driver.findElement(By.name("password")).sendKeys("xxx");
driver.findElement(By.name("button0")).click();
I think your problem is the following:
This line: driver.get(baseUrl + "/something.com"); says him to go to this page, and the second line says him to search for the element immediately (so the browser dont have time at all to load the page)
So try this:
WebDriverWait wait;
wait = new WebDriverWait(webdriver, 10);
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("user")));
}catch(TimeoutException e){
verifyElementPresent(locator);
}
or:
for (int second = 0;; second++) {
if (second >= 60)
fail("timeout");
try {
if (isElementPresent(By.name("user"))) {
break;
}
} catch (Exception e) {
}
Thread.sleep(1000);
}
Are you bound to the Driver? you could try this:
Selenium selenium = new WebDriverBackedSelenium(driver,"http://example.com");
selenium.open("http://something.com");
and optionally a
selenium.waitForPageToLoad();
The other things you tried to do are also simpler with the WebDriverBackedSelenium like
selenium.type(String field,String text);
you can look at that for the javadoc and deeper explanation
I stop for some days this project, and today i resolve the trouble.
This is the code:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
WebElement body = driver.findElement(By.name("body"));
driver.switchTo().frame(body);
I hope this help someone.
Thanks.

Java Error Catching Issue

I have a try/catch thing set up where it will catch all exceptions and then display the error.
Here is my code:
try {
//CODE THAT COULD ERROR HERE
} catch (final Exception e) {
System.err.println("Unexpected error: " + e.getStackTrace()[0]);
}
The above code gives me the LAST class that had the error. How do I detect the LAST class of MY PROGRAM that had the error?
Example Output: "Unexpected error: package.ClassName.method(ClassName.java:46)"
I want it to output the line of my program that had the error, not the line of a built-in java class that error-ed because of my program.
e.printStackTrace()
might make you happier. Or print the top of the array of stack trace entries available from the appropriate method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace()
returns them. The first one is what you are asking for.
You can use getStackTrace to get an array of StackTraceElement instances, and filter that based on your package and/or class names (using getClassName for each element, which gives you the fully-qualified class name for that stack trace frame). That would let you winnow it down to your code rather than the JDK class the exception originated in.
try {
//error producing code
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
if (!s.getClassName().startsWith("java.")) {
System.out.println("file name: " + s.getFileName());
System.out.println("class name: " + s.getClassName());
System.out.println("method name: " + s.getMethodName());
System.out.println("line number: " + s.getLineNumber());
System.out.println();
//break; // will be the highest non java package...
}
}
}
You of course could switch it to be package specific so if (s.getClassName().startsWith("com.company")) { so it wont return for a third party library or something in the sun package or other non java package.

Categories