Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to throw an exception sooner than later?

Today I encountered the following situation: ("pseudo code")

class MyClass {

    public void workOnArray(Object[] data) {
        for (Object item : data) {
            workOnItem(item);
        }
    }

    public void workOnItem(Object item) {
        if (item == null) throw new NullPointerException();
    }
}

Now if the caller calls workOnArray with an array containing null items, the caller would get a NullPointerException because of workOnItem.

But I could insert an additional check in workOnArray, in other words, the problem can be detected sooner.

(Please note that this is a trivial example, in a real life application this can be much less obvious).

On the pro side I'd say an additional check could offer more high-level diagnostic information. Also failing early is always a good thing.

On the contra side I'd ask myself "If I do that, shouldn't I also validate each and every parameter passed into the core API of my programming language and throw the exact same exceptions?"

Is there some rule of thumb when to throw exceptions early and when to just let the callee throw it?

like image 869
Daniel Rikowski Avatar asked Dec 28 '22 06:12

Daniel Rikowski


2 Answers

In the case of a loop processing items like that, there's one thing that would definitely make me want to pre-validate the whole array of items first; If it would be bad for some of the items to be processed before an exception was thrown, leaving any remaining items un-processed.

Barring some sort of transaction mechanism wrapping the code, I would usually want to have some assurance that the items in the collection were valid before beginning to process them.

like image 129
Andrew Barber Avatar answered Jan 03 '23 08:01

Andrew Barber


In this example, the workOnItem method is the one that cares whether or not item is null. The workOnArray method doesn't care whether or not items are null and so IMO shouldn't validate whether or not any items are null. The workOnItem method does care and so should perform the check.

I would also consider throwing a more appropriate exception type from workOnItem. A NullPointerException (or in C#, NullReferenceException) often indicates some unexpected flaw in the operation of a method. In C#, I would be more inclined to throw an ArgumentNullException that includes the name of the null parameter. This more clearly indicates that workOnItem can't continue because it cannot handle receiving a null argument.

like image 42
John Bledsoe Avatar answered Jan 03 '23 07:01

John Bledsoe