Java Optional Throw Exception
By AmarSivas | | Updated : 2022-03-23 | Viewed : 94 times

In this current tutorial, we are going to learn about the usage of the
Table of Contents:
Java Optional Throw Exception
.Let's spend some time understanding the below-given syntax in Java 8.
if(optionalValue.isPresent()) {
}
optionalValue.get().orElseThrow( () -> throw new ObjectNotFoundException("Optional value is empty.))
We can write the same code as below
if(!optionalValue.isPresent()) {
throw new ObjectNotFoundException("Optional value is empty.))
}
Notice the first one is very simple and readable. We can understand very better when we have a nice example as below.
public class EmployeeUtils {
public Employee getEmployeeByName(String name) throws Exception {
Employee employee = null;
if (!name.isEmpty()) {
employee = new Employee();
}
return Optional.ofNullable(employee)
.orElseThrow(() -> new EmployeeNotFoundException("Employee is not existed with given Name."));
}
public Employee getEmployeeById(Integer id) throws Exception {
Employee employee = null;
if (id != null) {
employee = new Employee();
}
return Optional.ofNullable(employee)
.orElseThrow(() -> new NullPointerException("Employee is not existed with given Id."));
}
}
public class EmployeeUtilsTest {
@Test
public void getEmployeeByNameTest() throws Exception {
Exception exception = assertThrows(EmployeeNotFoundException.class, () -> {
new EmployeeUtils().getEmployeeByName("");
});
String expectedMessage = "Employee is not existed with given Name.";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
public void getEmployeeByIdTest() throws Exception {
Exception exception = assertThrows(NullPointerException.class, () -> {
new EmployeeUtils().getEmployeeById(null);
});
String expectedMessage = "Employee is not existed with given Id.";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
}
We used here customized exceptions using with
public Address getAddressByEmployeeId(Integer id) throws Exception {
Address address = null;
if (id != null) {
address = new Address();
}
return Optional.ofNullable(address).orElseThrow();
}
@Test
public void getAddressByEmployeeIdTest() throws Exception {
Exception exception = assertThrows(NoSuchElementException.class, () -> {
new EmployeeUtils().getAddressByEmployeeId(null);
});
String expectedMessage = "No value present";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
The entire code is been added to this GitHub repo Java-Optional-Throw-Exception-Example-App.