0

I need to create a method to find an employee by employee's name. There are three possible solution to implement this as below :

  1. Employee findEmployeeById(long empId) throws NoSuchEmployeeCheckedException;
  2. Optional findEmployeeById(long empId);
  3. 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)

  1. Is the findEmployeeById a recoverable conditions?
  2. Do i need to use Optional or throw exception?
  3. which solution is best?
jason zhang
  • 431
  • 5
  • 11

1 Answers1

0

Use exceptions for exceptional circumstances, if it is commonly expected for no employee to be found then you probably shouldnt use an exception.
Exceptions also have some runtime overhead as they need to capture the stack trace.
In this circumstance I would use either an Optional or if multiple employees can have the same name, return some type of Collection, use an empty collection if no employee is found.

Magnus
  • 7,952
  • 2
  • 26
  • 52