Programming Practices – Using Exceptions to Catch Errors Early

error handlingexceptionsprogramming practices

I use exceptions to catch problems early. For example:

public int getAverageAge(Person p1, Person p2){
    if(p1 == null || p2 == null)
        throw new IllegalArgumentException("One or more of input persons is null").
    return (p1.getAge() + p2.getAge()) / 2;
}

My program should never pass null in this function. I never intend it to. However as we all know, unintended stuff happens in programming.

Throwing an exception if this problem occurs, allows me to spot and fix it, before it causes more problems in other places in the program. The exception stops the program and tells me "bad stuff happened here, fix it". Instead of this null moving around the program causing problems elsewhere.

Now, you're right, in this case the null would simply cause a NullPointerException right away, so it might not be the best example.

But consider a method such as this one for example:

public void registerPerson(Person person){
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}

In this case, a null as the parameter would be passed around the program, and might cause errors much later, which will be hard to trace back to their origin.

Changing the function like so:

public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}

Allows me to spot the problem much before it causes weird errors in other places.

Also, a null reference as a parameter is only an example. It could be many kinds of problems, from invalid arguments to anything else. It's always better to spot them early.


So my question is simply: is this good practice? Is my use of exceptions as problem-preventing tools good? Is this a legitimate application of exceptions or is it problematic?

Best Answer

Yes, "fail early" is a very good principle, and this is simply one possible way of implementing it. And in methods that have to return a specific value, there isn't really very much else you can do to fail deliberately - it's either throwing exceptions, or triggering assertions. Exceptions are supposed to signal 'exceptional' conditions, and detecting a programming error certainly is exceptional.