Search code examples
javaexceptionmethodsthrow

Java Best way to throw exception in a method


I have created my own type of exception and want to implement it in a method. As of now I have written it in the following way, and it works.

public Worker remove (String firstName, String lastName, String number) throws NoSuchEmployeeException {
Worker w = null;
for (int i = 0; i < list.size(); i++) {
  if (list.get(i).getFirstName().compareTo(firstName) == 0 &&
      list.get(i).getLastName().compareTo(lastName) == 0 &&
      list.get(i).getNumber().compareTo(number) == 0) {
    w = list.get(i);
    list.remove(i);
  }
  else
    throw new NoSuchEmployeeException(/*"Employee could not be found"*/);
}
return w;
}

What I would like to know is if this is the best way to do it or if there is any other more appropriate/efficient/correct way of doing it. And also, do I need to declare the exception in the method header?

Thanks in advance.


Solution

  • I'm not going to comment on whether or not to use checked vs unchecked exceptions as that will provoke a monster debate.

    If you create a checked exception, then yes it must be thrown in the method signature. If you create an unchecked e.g. extends from RuntimeException then you do not need to throw it in the method signature.

    Checked exceptions are generally exceptions that are recoverable. Unchecked exception are irrecoverable.