1

Sorry if this is a duplicate question, I did some searching and couldn't find my specific scenario.

I was wondering if I could get some advise on the best way to deal with null exception errors with functions that try and return an object from an ArrayList by an ID if the parsed ID isn't found in the index of the ArrayList.

I have a Project class that has an ArrayList of Task objects:

private ArrayList<Task> tasks = new ArrayList<Task>();

and I have a getting function in the Project class to try and return a Task by it's ID from the ArrayList:

public Task getTask(int id)  {
    if(id > 0 && id <= tasks.size()) {
        for(Task task : tasks) {
            if(task.getID() == id) {
                return task;
            }
        }
    } else { 
        Globals.log("Couldt find Task with ID of: " + id + " in Project: " + title); 
    }
    return null;
}

When I try and call a function in a Task by getting a Task from ID, if the Tasks ID doesn't exist in the index of the ArrayList, naturally I get a null exception error, eg if there is no Task with an ID of 15, this code will fail with a null exception pointer:

project.getTask(15).addTag("Test");

My question is, can I do some error handling in the getTask(int id) function to log the error before the program crashes?

I've tried adding a try {} catch {} block around it, but it still doesn't run my Globals.log() function before it crashes.

Adding a try {} catch {} block works if I do the error handling in the addTag(); function in the Task class, but I would rather not have to go through all my functions in the Task class and add try {} catch {} to every function.

Is there a better solution to this problem?

1
  • Why crash at all? Task task = project.getTag(15). if (task!=null){task.addTag("Test");} else {do your reporting} Commented Feb 6, 2020 at 4:20

4 Answers 4

3

From java 8 you can use Optional as return type if Task is present in array return Optional with Task else empty Optional

public Optional<Task> getTask(int id)  {
if(id > 0 && id <= tasks.size()) {
    for(Task task : tasks) {
        if(task.getID() == id) {
            return Optional.of(task);
        }
    }
} 

 Globals.log("Couldt find Task with ID of: " + id + " in Project: " + title); 

return Optional.empty();
}

And from Optional you can use ifPresent by avoiding try-catch and null check also

project.getTask(15).ifPresent(t->t.addTag("test"));
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, exactly what I was after! Thank you very much! :)
1

I think Deadpool solved the NPE issue, but there is another slight oversight in your code.

If in the case of the IDs not being sequentially ordered then your first check if(id > 0 && id <= tasks.size()) will cause issues and removing it would be a good idea:

public Optional<Task> getTask(int id) {
    for (Task task : tasks) {
        if (task.getID() == id) {
            return Optional.of(task);
        }
    }

    Globals.log("Couldt find Task with ID of: " + id + " in Project: " + title);

    return Optional.empty();
}

1 Comment

Yeah your right, that check is redundant with the Optional implementation. Thank you for the suggestion.
0

Do not use try/catch in this case.

You need to check if getTask method return NULL value before using it like this:

public void test() {
   Task task = project.getTask(15);
   if (task != null) {
      task.addTag("Test");
   }
}

Comments

0

Try this

Task taskObj=null;

        for(Task task : tasks) {
            if(task.getID() == id) {
                taskObj= task;
            }
        }
    if(taskObj!=null)
    { 
        return null;
    }else{
        Globals.log("Couldt find Task with ID of: " + id + " in Project: " + title); 
        return null;
    }
}

public void mainClass() {
   Task task = project.getTask(15);
   if (task != null) {
      task.addTag("Test");
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.