Exception Handling in JUnit

1 min read

Lets say we have the following method that receives 2 integer values divides them and returns the result or throws an ArithmeticException if an error occurs:

public class Calc {
public int divide(int x,int y) throws Exception {
return x/y;
}
}

As the method divide specifies that it can throw an ArithmeticException its not necessary to write the unit test code in a try-catch block:

//Avoid this approach
@Test
void shouldThrowException() {
try {
assertEquals(2,new Calc().divide(4,0));
} catch(ArithmeticException e) {
e.printStackTrace();
}
}

So, instead you can use the following alternative that offers a short and more clear solution:

//Do this instead
@Test
void shouldThrowException() throws Exception {
assertEquals(2,new Calc().divide(4,0));
}
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts