Throw an exception or prevent it?

The question is whether he prefers Throw

a exception

or to prevent it from appearing. This is for a game project.

IndexOutOfBoundsException

against coding around it.

I have List<E>

private Attribute<List> attributes;

      

The method for getting an item by index.

public Attribute getAttribute (int index) {
    if (index < 0 || index >= attributes.size())
        index = 0;

    return attributes.get(index);
}

      

In this case, I am not executing the first element of the list.

+3


source to share


3 answers


Failure fast is usually a good idea: if an index of -1 is passed to this method, it probably means there is an error in the code calling the method. If you silently use index = 0 instead of: (a) the calling code might not get the expected result, and (b) you might not notice the error until it gets pretty messy to fix.

So I would just use:



public Attribute getAttribute (int index) {
    return attributes.get(index);
}

      

which will throw an exception if required. If the code that calls this method is error-free, then this exception should never be thrown.

+8


source


In this case, pretending that the index exists and is the same element as the first element is confusing and can lead to subtle errors.



Here I would pick IndexOutOfBoundsException

if the index is out of range. Note that other code that calls this must be prepared to catch this exception and handle it appropriately.

+4


source


The answer is very situational. In general, you want to handle exceptions elegantly whenever possible. That is, try to allow / ignore them where you can. The IndexOutOfBoundsException is often an example of where this is not possible.

Hard breaks due to exceptions are the last one. Do this only if your program cannot continue.

This question has a nice post. When to throw an exception?

+1


source







All Articles