I need to create a method to find an employee by employee's name. There are three possible solution to implement this as below :
- Employee findEmployeeById(long empId) throws NoSuchEmployeeCheckedException;
- Optional findEmployeeById(long empId);
- Employee findEmployeeById(long empId) throws NoSuchEmployeeUnCheckedException;
The first method will returning an instance of employee if the id matched in my repository, otherwise throw an instance of check exception NoSuchEmployeeCheckedException
The second method will returning an instance of java8's Optional, while no exception throw.
The last method is similar with the first one , but throw an instance of UnCheck exception NoSuchEmployeeUnCheckedException
instead of checked exception.
I have read multiple posts on StackOverFlow about checked vs unchecked exceptions. I'm honestly still not quite sure how to use them properly.
Joshua Bloch in "Effective Java" said that
Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)
- Is the findEmployeeById a recoverable conditions?
- Do i need to use Optional or throw exception?
- which solution is best?