Java Optional Throw Exception

By | | Updated : 2022-03-23 | Viewed : 179 times

Java Optional Throw Exception

In this current tutorial, we are going to learn about the usage of the elseThrow() method in Optional in Java 8.

Table of Contents:

Java Optional Throw Exception

.Let's spend some time understanding the below-given syntax in Java 8.

ifPresent() in Optional
if(optionalValue.isPresent()) {
}

ifPresent() method can identify whether optionalValue is empty or not.

orElseThrow() will be considered when optionalValue is empty and need an exception to be thrown.

Java Optional Throw Exception
optionalValue.get().orElseThrow( () -> throw new ObjectNotFoundException("Optional value is empty.))

We can write the same code as below

Throwing Exception In Java
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.

EmployeeUtils.java
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."));
    }
}
EmployeeUtilsTest.java
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 orElseThrow(). We can use it without any exception as well. But here default exception is been thrown which is NoSuchElementException.

EmployeeUtils.java
public Address getAddressByEmployeeId(Integer id) throws Exception {
        Address address = null;
        if (id != null) {
            address = new Address();
        }
        return Optional.ofNullable(address).orElseThrow();
    }
EmployeeUtilsTest.java
@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.

Leave A Reply