Throw new Exception and have a block where one catches any exception - java

private WebElement findElementByXpath(WebDriver driver, String xpath) throws WebElementNotFoundException, HopelessAccountException {
WebElement element = null;
try {
element = new WebDriverWait(driver, Duration.ofSeconds(dirationInSeconds))
.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
} catch (TimeoutException timeoutException) {
loggingService.timeMark("findElementByXpath", "TimeoutException");
throw new WebElementNotFoundException();
} catch (UnhandledAlertException alertException) {
loggingService.timeMark("findElementByXpath", "alertException");
final String LIMITS_EXHAUSTED_MESSAGE = "Not enough limits!";
String message = alertException.getMessage();
if (message.contains(LIMITS_EXHAUSTED_MESSAGE)){
throw new HopelessAccountException(); // Attention.
}
} catch (Exception e) {
// Mustn't be here.
loggingService.timeMark("findElementByXpath", e.getMessage());
driver.quit();
System.out.println("QUIT!");
System.exit(0);
}
loggingService.timeMark("findElementByXpath", "end. Xpath: " + xpath);
return element;
}
Please, have a look at the line that I commented as "Attention".
I have caught the exception where there is not enough limits any more. And I throw the exception that the account is hopeless.
But it is immediately caught by just after the next few lines. Namely where I commented "Mustn't be here".
I would like to preserve this catching any exception. At least for debugging purpose.
Could you help me understand whether I can both throw HopelessAccountException and preserve the "catch Exception" block?

You can always modify your Exception block to rethrow e if it is an instance of HopelessAccountException:
} catch (Exception e) {
if (e instanceof HopelessAccountException) throw e; // preserves original stack trace
// Mustn't be here.
loggingService.timeMark("findElementByXpath", e.getMessage());
driver.quit();
System.out.println("QUIT!");
System.exit(0);
}
However as #fishinear indicates, in your posted code the Exception block would not be reached as a result of the throw of throw new HopelessAccountException() - if your actual code looked more like:
try {
try {
System.out.println("In A()");
// do something to cause an exception E3 (e.g. UnhandledAlertException)
throw new E3();
} catch (E3 e3) { // UnhandledAlertException
System.out.println("In E3 catch");
throw new E1(); // HopelessAccountException
}
} catch (Exception e) {
System.out.println("In Exception catch");
if (e instanceof E1) throw e; // rethrow HopelessAccountException
System.out.println("e: "+e);
}
Then the test-and-rethrow is possible.
Then when you rip out your debugging "try block" your code would behave the same (for the HopelessAcountException).

in your code that calls findElementByXpath(…) you could catch the broad Exception type there. This means in your findElementByXpath(…) method you could just handle the known exceptions and anything else could be captured in calling code

Related

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

Using FindBugs in eclipse

I have been using Find Bugs in Eclipse and I can not figure out why some of the bugs are coming up or how to fix them. Any ideas or help would be great!
The first bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
The second bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
out.writeObject(accountMap.get(i));
I tried to change it to :
out.writeObject(accountMap.get(Integer.toString(i)));
The third bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not write file:" + fileName);
For the first bug this is with my try block as well. I am lost. I tried to follow you post below, but I am confused. Sorry, I am very new!
public ServerSolution() {
accountMap = new HashMap<String,Account>();
File file = new File(fileName);
ObjectInputStream in = null;
try {
if (file.exists()) {
System.out.println("Reading from file " + fileName + "...");
in = new ObjectInputStream(new FileInputStream(file));
Integer sizeI = (Integer) in.readObject();
int size = sizeI.intValue();
for (int i=0; i < size; i++) {
Account acc = (Account) in.readObject();
//CST316 TASK 1 CHECKSTYLE FIX
if (acc != null) {
accountMap.put(acc.getName(), acc);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
See FindBugs Bug Description:
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}

Handling contained exceptions

I'm wondering how should one handle "contained" exceptions. Because the term isn't concrete enough, let me take an example of PrivilegedActionException.
In short, this exception will in its cause contain any checked exception thrown during the computation within PrivilegedAction.
Now if I have and method computate() throws IOException I'll - if executed on its own - handle it as:
try {
computate();
} catch (FileNotFoundException ex) {
// Handle file not found
} catch (SomeOtherSubtypeOfIOException ex) {
// handle that again
}
Now as this has been executed in PriviledgedAction the only exception I get is PrivilegedActionException:
try {
Subject.doAs(() -> computate());
} catch (PrivilegedActionException ex) {
// Now what?
}
I can get the IOException from previous example by calling ex.getCause() but how would that look like? The obvious way looks odd ...
catch (PrivilegedActionException ex) {
if (ex.getCause() instanceof FileNotFoundException.class) {
// handle FileNotFound
} else if (ex.getCause() instanceof xxx) {
// something else
}
}
You could get the cause and re-throw it. Then handle exception with an outer try-catch.
catch (PrivilegedActionException ex) {
Throwable cause = ex.getCause();
if(cause !=null) throw ex.getCause();
else ex.printStackTrace();
}

Why Findbugs cannot detect my code error?

I have read the bug detectors in findbugs website, http://findbugs.sourceforge.net/bugDescriptions.html
I want to write a test code and use Findbugs to detect the REC error.
But the findbugs cannot. Why? Could you help me to solve this?
Thanks,
Below is the description in Findbugs.
REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
My code is:
public static void test1(){
int A[] = {1,2,3};
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
try {
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}
The try is where the exception occur that you want to catch. However, since it is occurring out of the try block, the exception is not caught by the catch part, which is why FindBugs reporting it as a useless try {...} catch {...} code. The proper code should be as follows.
int A[] = {1,2,3};
try {
int result = 5/0;//divided by 0
int arrOut = A[0]+A[4];//index out of bound
System.out.println(arrOut);
System.out.println(result);
} catch (RuntimeException e) {
// TODO: handle exception
System.out.println("Runtimeex throw");
throw e;
} catch (Exception e) {
// TODO: handle exception
System.out.println("An try error occurred: 0 cannot be divided");
}
}

Java throw e becomes null on Android

I have the following:
try {
response.statusCode = urlConnection.getResponseCode();
} catch(IOException e) {
throw e;
}
I look at the debugger and e = UnknownHostException
After the throw I have:
try {
NetworkResponse response = NetworkHelper.getByURL(url);
} catch(Exception e) { <------- IT LANDS HERE, BUT e=null
ExceptionHelper.announce(e);
throw e;
}
So after the throw my catch block gets the exception but it's null.
The debugger shows e=null.
I have no idea why this would happen.
I don't even see the point of catching the exception if you just immediately rethrow it. Add a throws IOException to that method and let the other catch handle it.

Categories