Handling exceptions

Exception handling is an important part of Java coding. The Java community follows a set of best practices about exception handling. The following are the exception handling best practices for unit testing:

  • Do not write catch blocks to pass a unit test. Consider the following example where a Calculator program has a divide method. It takes two integers, divides, and returns a result. When divide encounters a divide by zero, the program should throw an exception. The following is the code:
    public class Calculator {
    
      public int divide(int op1, int op2)  {
        return op1/op2;
      }
    }

    The following is the test:

    @Test public void divideByZero_throws_exception() throws Exception { try { calc.divide(1, 0); fail("Should not reach here"); } catch ...

Get Mastering Unit Testing Using Mockito and JUnit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.