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.
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.
In case you have some other information other than error message to be sent out along with the exception.
You will need to first create the Object of the Exception
set values you want to throw in the Exception
Or you can write your own constructors for the Exception which would take different values and exception message to create object to the Exception you wanna throw.
As such
throw new NoSuchEmployeeException(/*"Employee could not be found"*/);
is fine
1 Your code would be more efficient if you implemented Comparable and the compareTo
method in Worker as follows -
@Override
public int compareTo(Object obj) {
// identity.
if (obj == this) {
return 0;
} else if (obj instanceof Worker) {
Worker w = (Worker) obj;
if (w.getNumber().compareTo(number) != 0) {
return w.getNumber().compareTo(number);
} else if (w.getLastName().compareTo(lastName) != 0) {
return w.getLastName().compareTo(lastName);
}
return w.getFirstName().compareTo(firstName);
}
return -1;
}
And then use the SortedSet collection type (e.g. TreeSet<Worker>
), especially the remove method.
2 You should probably just return null. Throwing an Exception
is certainly your choice, but (IMO) an unchecked Exception
should be reserved for unrecoverable errors.