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?