Home > front end >  Find an Employee by Name and throw a custom Exception if the given name was not Found
Find an Employee by Name and throw a custom Exception if the given name was not Found

Time:06-04

I am trying to prepare an employee search program.

Requirements:

  • I have an ArrayList "employee" which is holding data of multiple employees (like : name, employeeID, location, DOJ, etc).

  • I need to prepare a method say findEmployee which will expect a name as input, and will return all the associated details with that employee.

  • In case no such employee was found, then it should throw an exception.

My code:

private static List<Employee> employee = new ArrayList<>();

public Employee findEmployee(String Name) throws emplyeeNotFoundException {

    for(Employee value : employee) {
        if(value.getName().equals(Name)) {
            return value;
        }
        else {
            throw new emplyeeNotFoundException(Name);
        }
    }
}

Here Employee is the main class and getName() is the method to get the name of employee.

Issue:

  • I am aware that above logic will not work as it will throw an exception every time if condition does not meet the requirement.

Can anyone suggest me how I need to write this code so that it will check the complete employee list and only throw exception when no data found?

Also, if it found the employee name in ArrayList it should return all its details and come out of the loop?

CodePudding user response:

public Employee findEmployee(String Name) throws emplyeeNotFoundException {
    boolean isFound = false;
    for(Employee value : employee) {
        if(value.getName().equals(Name)) {
            return value;
        }
    }
    throw new emplyeeNotFoundException(Name); 
}

If the value is present, returns the value.
If not present, the loop ends and at this point nothing is returned. Hence the Exception is thrown.

CodePudding user response:

You can throw exception after loop over all the array (meaning you dont fount any employee), and if do found the function will end on the return.

private static List<Employee> employee = new ArrayList<>();

public Employee findEmployee(String Name) throws emplyeeNotFoundException {
  for(Employee value : employee) {
    if(value.getName().equals(Name)) {
      return value;
    }
  }
  throw new emplyeeNotFoundException(Name);
}

CodePudding user response:

it will throw an exception every time if condition does not meet the requirement

No, that's not correct. An exception will be thrown only once if the very first employee in the list has a name which is different from the target name.

The method will be deallocated from the stack, i.e. its execution will be terminated. And exception will be propagated to the calling method. If the caller will not be able to handle it, the exception will be propagated further.

To prevent it, you need to place the throws clause outside the loop:

public Employee findEmployee(String Name) throws emplyeeNotFoundException {
    
    Employee result = null;
    
    for (Employee value : employee) {
        if (value.getName().equals(Name)) {
            result = value;
            break;
        }
    }
    if (result == null) {
        throw new emplyeeNotFoundException(Name);
    }

    return result;
}

In my personal opinion, it's better to avoid returning from the middle of the method. It makes the code more structured and easier to read.

And since you've specified the tag here another solution using Stream API.

Stream-based solution

You can use apply filter() with your condition and then findFirst() as a terminal operation, which will produce an optional result Optional<Employee>.

And finally, apply orElseThrow() on the optional object, that will either retrieve the employee or will throw an exception if optional is empty.

One of the flavors on orElseThrow() expects a supplier as an argument, so we can the exception that be thrown if result wasn't found.

return employee.stream()
    .filter(emp -> emp.getName().equals(name))
    .findFirst()
    .orElseThrow(() -> new EmplyeeNotFoundException(name));

Sidenote:

  • adhere to the Java naming conventions when you're giving names to your classes, methods, etc. Names of classes should start with a capital letter - EmplyeeNotFoundException, and variable-name with a lower case letter - name.
  • Related