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@Testvoid 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@Testvoid shouldThrowException() throws Exception { assertEquals(2,new Calc().divide(4,0));}