try/catch a void type

4.3k views Asked by At

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.

3

There are 3 answers

3
nafas On BEST ANSWER

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

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

I think instead of doing assert you should use the @Expected annotation which expects for the DuplicateException since its a test case