Java – throw an exception or block it?

The question is whether it prefers to throw exceptions or prevent exceptions This is a game project

The index out of boundary exception is related to coding

I have a list < E >

private Attribute<List> attributes;

A method of obtaining items by index

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

    return attributes.get(index);
}

In this case, I default to the first element of the list

Solution

Quick failure is usually a good idea: if you pass the index of - 1 to the method, it may mean that there is an error in the code calling the method If you silently use index = 0, (a) the calling code may not receive the expected results, and (b) you may not notice the error until it becomes very chaotic

So I just want to use:

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

If necessary, an exception is thrown If the code calling this method has no errors, the exception should never be thrown

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>