Emz
Emz

Reputation: 1280

Throw Exception or prevent it?

The question is if it is prefered to Throw an exception or to prevent it from ever occurring. It is for a game project.

IndexOutOfBoundsException vs. coding around it.

I have a List<E>

private Attribute<List> attributes;

A method to get 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 defaulting to the 1st element of the list.

Upvotes: 3

Views: 103

Answers (3)

Bryan Davis
Bryan Davis

Reputation: 134

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

Hard breaks because of exceptions is a last-resort. Do this only when your program cannot continue.

This question's answer has a good post on it. When to throw an exception?

Upvotes: 1

assylias
assylias

Reputation: 328598

Failing fast is generally a good idea: if an index of -1 is passed to that method, it probably means that there is a bug in the code calling the method. If you silently use index = 0 instead, (a) the calling code may not receive the expected result and (b) you may not notice the bug until it has become quite a mess to fix.

So I would simply use:

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

which will throw an exception if required. If the code calling this method is bug free, that exception should never be thrown.

Upvotes: 8

rgettman
rgettman

Reputation: 178263

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

Here I would throw an 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.

Upvotes: 4

Related Questions