简体   繁体   中英

How to throw a data exception if an element does not exist in Array?

So i have an arraylist of strings, im currently using a method so the user can access and return certain elements from the arraylist by inputting an index number.

I want to throw my own Data Exception if they try to access the index number of something which is not in the array. At the minute it is throwing an Index out of bounds exception. Currently im using the if statement below however it is not working! How can i do this?

if (set.get(index) == null) {
        throw new DataException("Record does not exists!");
    }

Attempting to access an out-of-bounds index from an ArrayList will always throw an IndexOutOfBounds exception. To fix this, you have two options. You can either avoid asking for the element until you're sure it exists or you can catch the error.

To catch the error, you would use a try-catch block like so:

try {
    someVariable = set.get(index);
} catch(Exception e) {
    throw new DataException(...);
}

To avoid triggering the error in the first place, you can just make sure the index is within the bounds of the ArrayList like so:

if(index < 0 || index >= set.size()) {
    throw new DataException(...);
}

You just need to test that the index is neither negative nor superior or equal to the list size:

if ( index < 0  || index >= list.size() ) {
    throw new DataException("Record does not exists!");
}

As the List.get(int index) javadoc stays :

Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Now I am not sure that it is good idea to wrap IndexOutOfBoundsException in a DataException .
It is a programming error to access to an index of of bounds of the array.
IndexOutOfBoundsException conveys very well this idea while

throw new DataException("Record does not exists!"); may be understood as a client error.

change the condition to:

if(index < 0 || index >= set.size()){
     ... 
}
if (index < 0 || index >= set.size() || set.get(index) == null) {
    throw new DataException("Record does not exists!");
}

Test that the index is within the ArrayList before executing the get () to avoid the IndexOutOfBoundsException. If either of the first 2 conditions are true, the get() is not reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM