Search code examples
arrayslistexceptionnullthrow

The point of throwing exceptions


What's the point of throwing exceptions? For example I stumbled across this:

static List<Integer> list(int [] a) {
    if (a == null)
        throw new NullPointerException();
        //...

But when you don't throw the nullpointer, you'll also get a nullpointer? I see this regularly and I wanted to know if this is a good habit to learn?


Solution

  • It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.