Java) Exception processing and filtering out conditions in the if statement

Asked 2 years ago, Updated 2 years ago, 56 views

It's nothing much, but I had to delete items from List<> specific indexes while making the code.

This code is applicable.

public boolean removeDetails(int index) 
{
        if(routineDetailModels == null || index >= routineDetailModels.size() || index < 0)
            return false;
        this.routineDetailModels.remove(index);
        return true;
    }

routineDetailModels is List<>.

As you can see, before you delete the items in the index position of this list, you can safely check the null and check if you delete the index that doesn't exist.

Doing it like this and just...

this.routineDetailModels.remove(index);

Is it better to leave this code and send an exception to the place where you called me with throws? (I'm thinking of sending a toast message in case of an exception because it's Android.)

For your information, this method returns boolean, but in fact, I'm trying to change it to void because I don't have to use it as a return value at the place I call.

When I tried to change it to void, the condition of that if statement is not null, but the index is smaller than size and the index is larger than zero.

If the Else situation comes out, it's ambiguous to write the corresponding code.

I'm asking because I'm curious about what to do better.

java exception

2022-09-20 18:01

1 Answers

In the overall code flow, it seems to be a problem that will be selected depending on the nature of the method.

If routineDetailModels is null and there is an obvious scenario in which the method will be invoked, try-catch is not suitable for use with this common control flow.

The typical wrong usage of try-catch is as follows

try {
    int i = 0;
    while(true)
        range[i++].climb();
} } catch (ArrayIndexOutOfBoundsException e) {

}

This is an example where try-catch was used to terminate the loop. This is also an incorrect example because it was used for general control flows.

Therefore, if it is for null and index check in terms of code stability, I think it is closer to the validity of use in terms of try-catch syntax usage.

It would also be helpful to refer to the Exceptions section of Effective Java.


2022-09-20 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.