Exceptions

Finally, we need to handle some exceptional cases. What happens if we call max(), min(), mean(), or median() if the DataSet is empty? We need some way to tell anyone using our DataSet that those methods shouldn’t be called on an empty DataSet. The way to do this in Java is to throw an exception.

Let’s change that behavior to throw an IllegalStateException if the DataSet is empty. Add the following code to the beginning of each of those four methods in DataSet.java

if (data.isEmpty()) {
    throw new IllegalStateException("DataSet is empty");
}

Now we just need to add some assertions to our test code to make sure that when we call those methods with an empty DataSet, we get an exception. To test that an expression throws a particular exception, we need to use assertThrows with some new syntax. Here’s the test for max().

assertThrows(IllegalStateException.class, () -> ds.max());

The first argument, IllegalStateException.class, says that the expression under test should throw an IllegalStateException. The second argument, () -> ds.max(), is Java’s syntax for an anonymous method that takes no arguments and simply computes ds.max().

Add similar assertions to each of the four methods that should throw an exception. Make sure you change ds.max() to call the appropriate method for each test.

Now make sure to submit the changes you made to git (i.e., the DataSet.java and DataSetTest.java files).