Вопрос

public void onClick(int row) {
    if (mItems.size() <= row) {
        return;
    }
    Action action = mItems.get(row);
}

Is it safe to call mItems.get()?

EDIT: From crash log, the row is -1, and then throw the exception.

EDIT: The safe writing is:

if (row < 0 || row >= mItems.size()) {
...
}
Это было полезно?

Решение

If the question is , will this code throw an ArrayIndexOutOfBoundsException then following case will

If a negative value is passed to row , this code with end up in an java.lang.ArrayIndexOutOfBoundsException

Другие советы

ArrayIndexOutofBoundsException is an unchecked exception. Therefore, the java compiler will not check if a given block of code throws it.

If this exception is being thrown, then you are indexing out of the bounds of the array - as the name of the exception tells you.

Link discussing checked and unchecked exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

EDIT: In your particular instance, is another thread accessing mItems? Because that could make the size of mItems change between the moment you check its size and the moment you index into it.

Yes, it looks safe.

Your question doesn't seem to show your effort or research on the given problem. Have you tried to compile and test run the code with certain values of row?

You could have figured it out by yourself while doing so.

you can throw any type of exception no matter it is checked or unchecked.

only thing is for checked compiler forces you to handle but for unchecked like ArrayIndexOutOfBound exception compiler wont complaint.

in your code you can throw it like below

public void onClick(int row) {
    if (mItems.size() <= row) {
        throw new ArrayIndexOutOfBoundsException();
    }
    Action action = mItems.get(row);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top