I am new to programming and have a noob question. I am trying to run a test like so...
#Test
public void rememberTest()
throws DuplicateException{
try{
personA.remember(sighting4);
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
try{
assertEquals(personA.remember(sighting3), "The list already contains this sighting");
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
}
the first try/catch compiles but the second one does not. It tells me "'void' type not allowed here.
" Why can't I use a void? If I can't use a void type, then how would I build my test so that the exception is thrown?
some background info: rememberTest is a test of the remember method that adds an item to an ArrayList.
the remember method, in Class Person, is as follows:
public void remember(final Sighting s)
throws DuplicateException
{
if(lifeList.contains(s)) {
throw new DuplicateException("The list already contains this sighting");
}
lifeList.remember(s);
}
If you need more info please request and I will post it as required.
since you method has already ensured that no duplicate value will be added then I suggest to remove the assertEquals from your code,
#Test
public void rememberTest()
throws DuplicateException{
try{
personA.remember(sighting4);
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
try{
personA.remember(sighting3), //this will throws Exception if sighting3 is already in.
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
}
to demonstrate edit your code to this:
#Test
public void rememberTest()
throws DuplicateException{
Sighting s1=//initialize s1
Sighting s2=s1;
try{
personA.remember(s1);
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
try{
personA.remember(s2), //This will throw an exception because s1 and s2 are pointed to the same object
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
}
I think instead of doing assert you should use the #Expected annotation which expects for the DuplicateException since its a test case
for the purpose of throwing the exception and catching it in the test Class, do some such thing as this:
try{
personA.remember(sightingSame);
}
catch (DuplicateException e) {
assertEquals("The list already contains this sighting", e.getMessage());
}
catch (Exception e) {
fail("Failed" + e.getMessage());
}
Related
I have a method which looks for animals species in a file and I'd like it to throw an error when a specie don't exist in my database
public void printAnimalFromNames(String... s){
try (Stream<String> stream = Arrays.stream(s)) {
stream.forEach(x -> printAnimalPage(AnimalInfo.get(findSpecie(x))));
} catch (Exception e){
System.out.println("this spiece don't seem to exist");
}
}
in my catch part I'd like to put the x variable that throw the exeption in my error explanation like
[...]
catch (Exception e){
System.out.println("this spiece "+x+" don't seem to exist");
}
how can I do ?
You'll have to move the try-catch inside the body of the lambda, as that's where the lambda parameter, x, is in scope:
public void printAnimalFromNames(String... s) {
try (Stream<String> stream = Arrays.stream(s)) {
stream.forEach(x -> {
try {
printAnimalPage(AnimalInfo.get(findSpecie(x)));
} catch (Exception e) {
System.out.println("this specie " + x + " don't seem to exist");
}
});
}
}
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();
}
I need to handle Exceptions which are raised by Catch block code in Java
Example, to "handle" an Exception:
try
{
// try do something
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e.getMessage());
//Do some more
}
More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
However if you want another catch in your try catch, you can do the following:
try
{
//Do something
}
catch (IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
try
{
// Try something else
}
catch ( Exception e1 )
{
System.out.println("Caught Another exception: " + e1.getMessage());
}
}
Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:
try {
// do something here
}
catch(IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
foo();
}
private void foo()
{
try {
// do something here (when we have the IO exception)
}
catch(Exception e)
{
System.out.println("Caught another exception: " + e.getMessage());
}
}
Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.
Example :
public int classicMethodInCaseOfException(int exampleParam) {
try {
// TODO
}
catch(Exception e)
{
methodInCaseOfException();
}
}
public int methodInCaseOfException()
{
try {
// TODO
}
catch(Exception e)
{
//TODO
}
}
Do as you would do in an usual try/catch situation :
try{
throw new Exception();
}catch(Exception e1){
try{
throw new Exception();
}catch(Exception e2){
//do something
}
}
You can add new try catch block in your main catch block.
try
{
int b=10/0;
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException occurred");
try
{
int c=20/0;
}catch(ArithmeticException e1)
{
System.out.println("Another ArithmeticException occurred");
}
}
I think the most clean way is to create method which is catching the exceptions occurs in its body. However it can be very dependent to the situation and type of code you are dealing with.
One example of what you are asking about is closing a Stream which is opened in a try-catch-finally block. For example:
package a;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
//TODO: Log the exception and handle it,
// for example show a message to the user
} finally {
//out.close(); //Second level exception is
// occurring in closing the
// Stream. Move it to a new method:
closeOutPutStreamResource(out);
}
}
private static void closeOutPutStreamResource(OutputStream out){
try {
out.close();
} catch (IOException e) {
// TODO: log the exception and ignore
// if it's not important
// OR
// Throw an instance of RuntimeException
// or one of it's subclasses
// which doesn't make you to catch it
// using a try-catch block (unchecked)
throw new CloseOutPutStreamException(e);
}
}
}
class CloseOutPutStreamException extends RuntimeException{
public CloseOutPutStreamException() {
super();
}
public CloseOutPutStreamException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CloseOutPutStreamException(String message, Throwable cause) {
super(message, cause);
}
public CloseOutPutStreamException(String message) {
super(message);
}
public CloseOutPutStreamException(Throwable cause) {
super(cause);
}
}
Here I illustrated a situation which the second level exception is occurring in the finally block, but the same can apply for the exceptions occur in the catch block.
In my point of view writing methods such as closeOutPutStreamResource can be useful because they are packaging a boiler plate code for handling very common exceptions and they are making your codes more elegant.
Also it would be your choice to catch and log the exception in closeOutPutStreamResource or to throw it to other layers of your program. But it would be more elegant to wrap this unimportant checked exceptions into RuntimeException without a need for catching.
Hope this would be helpful.
You can use try catch block any where in methods or in block, so you can write try catch in catch block as well.
try {
// master try
}catch(Exception e){
// master catch
try {
// child try in master catch
}catch(Exception e1){
// child catch in master catch
}
}//master catch
It's not necessary to have a nested try-catch block when catch block throws Exception as all answers here suggest. You can enclose the caller method with try-catch to handle that Exception.
Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}
In the example below, you can see that the IOException (named FOURTH) exception cannot be caught using the outer catch clause. Why is that?
I know exceptions can be caught if its thrown in a nested try block, using outer catch.
If you change the b static variable value to false then you can see this.
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
import java.io.*;
public class Exceptions {
static boolean b = true;
public static void main(String[] args){
try {
exceptions(b);
} catch (Exception e) {
System.out.println(e + " is handled by main().");
}
}
static void exceptions(boolean b) throws Exception{
try{
if(b) throw new FileNotFoundException("FIRST");
try{
throw new IOException("SECOND");
}
catch(FileNotFoundException e){
System.out.println("This will never been printed out.");
}
}
catch(FileNotFoundException e){
System.out.println(e + " is handled by exceptions().");
try{
throw new FileNotFoundException("THIRD");
}
catch(FileNotFoundException fe){
System.out.println(fe + " is handled by exceptions() - nested.");
}
try{
throw new IOException("FOURTH");
}
finally{}
}
catch(Exception e){
System.out.println(e + " is handled by exceptions().");
}
}
}
The output if b = true :
java.io.FileNotFoundException: FIRST is handled by exceptions(). java.io.FileNotFoundException: THIRD is handled by exceptions() - nested. java.io.IOException: FOURTH is handled by main().
The output if b = false:
java.io.IOException: SECOND is handled by exceptions().
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
You can. The problem is that your last catch(Exception e) is at the same level of nesting which is why it doesn't catch an exception thrown in a previous catch block.
Try nesting your try/catch blocks like this
static void exceptions(boolean b) {
try {
try {
if (b) throw new FileNotFoundException("FIRST");
try {
throw new IOException("SECOND");
} catch (FileNotFoundException e) {
System.out.println("This will never been printed out.");
}
} catch (FileNotFoundException e) {
System.out.println(e + " is handled by exceptions().");
try {
throw new FileNotFoundException("THIRD");
} catch (FileNotFoundException fe) {
System.out.println(fe + " is handled by exceptions() - nested.");
}
// will be caught by the nested try/catch at the end.
throw new IOException("FOURTH");
}
} catch (Exception e) {
System.out.println(e + " is handled by exceptions().");
}
}
Your structure is some thing like this
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
Here catch1 and catch2 are at same level, and the exception thrown from catch1 will not reach catch2.
Hence Your IOE will be thrown back to the caller . If you want to handle the exception with in the method, then follow some thing below
try{
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
}
catch(Exce 3) {
// your IO will be caught here
}