In this section, we will learn how to throw exceptions to effectively handle errors that may arise in our code.
Our ArraySet implementation from the previous section has a small error. When we add null to our ArraySet, we get a NullPointerException.
The probelm lies in the contains method where we check items[i].equals(x). If the value at items[i] is null, then we are calling null.equals(x) -> NullPointerException.
Exceptions cause normal flow of control to stop. We can in fact choose to throw our own exceptions. In python you may have seen this with the raise keyword. In Java, Exceptions are objects and we throw exceptions using the following format:
throw new ExceptionObject(parameter1, ...)
Let's throw an exception when a user tries to add null to our ArraySet. We'll throw an IllegalArgumentException which takes in one parameter (a String message).
Our updated add method:
/* Associates the specified value with the specified key in this map.
Throws an IllegalArgumentException if the key is null. */