Guide to “Optional<T> Class” - Throw exception with Optional
Welcome readers, Greetings for the day.
In this story, I’ll guide you through the use of the Optional class that was introduced in Java 8. Also will look, how to throw a custom exception when an Optional is empty.
Topics covered:
1. The purpose of Optional
2. Uses of Optional class API methods
3. Throw an exception when Optional is empty.
The purpose of the Optional is to provide a type-level solution. This means you can represent optional values instead of null references.
A container object which may or may not contain a non-null value. If a value is present, isPresent()
will return true
and get()
will return the value. — from the doc.
Let me take an example, suppose you are accessing a database to get a single result using your query (suppose you’ve used Data JPA). Now, what happens if your database does not have your result? Absolutely it will return null, and suppose if you’ve performed any direct operation over that result, then you will get your lovely exception, i.e. NullPointerException.
So to overcome such a situation you can use the Optional class while storing the result. And can check that it is really not null and it has some values.
Uses of Optional class API methods
Now let's talk about some simple examples, you can create an Optional object in many ways provided by API. And can be sure not to get a NullPointerException.
You can create an Optional object using of() method, it is a static method. Returns an Optional object with the given non-null value.
Note: here I’ve used Junit to make testing easy.
In the above example, isPresent() returns true as there is a value available. If you’ve written any code after the assertion line that will also get executed successfully.
When you create an object using of() method, you need to keep in mind that the argument passed to the of() method can’t be null. Otherwise, you will get a lovely NullPointerException. You can find the exact in the below example.
In some cases, if you expect some null values as input, that time you can use the ofNullable() method. It returns an Optional with the given value(if it is not-null), otherwise returns an empty Optional. Have a look in the below example.
You can also create an empty Optional object using the empty() static method.
In the above example, we have created an empty object using the empty() method. So, isPresent() will return false as there is no value available. If you’ve written any code after the assertion line that will also get executed successfully.
Checking the presence of value: using isPresent() and isEmpty()
You can also be sure that your Optional object contains a value or not by using isPresent() and isEmpty() methods. You can find it in the below example.
If you want to apply some actions if a value is present then you can use ifPresent(). Take a look at the below example, if a value is present then it will print the length of the string otherwise it will do nothing.
Get object/value using get() method.
Set the default value if the desired value is null. You can use orElse() method to set default values as per your requirement.
Get the object if a given condition is matched by using filter() method of Predicate Interface. filter() takes Predicate/condition as an argument and returns an Optional object. If the wrapped values pass the given condition the value is return as it is in the form of an Optional object, if fails then it will return an empty Optional Object.
Let’s take one day to day coding example, suppose you have an age filed with user object, now you want to specify some age range, i.e 18 ≥ age ≤ 60, then you can use filter() in a better way.
Now come to another topic is “ Throwing an Exception if the value is not present.” Sometimes you may need some user input, without them you can not proceed further and suppose user hasn’t provided such values. So that time you can raise an exception using orElseThrow().
Take another example, suppose you are writing REST API, there you have a method which accepts an id of the user, and based on that you are finding the user record. But meanwhile, the user has provided some wrong Id, so that time you are not able to fetch the required data from DB. So you may need to raise an exception, that is possible by the use of orElseThrow().
In the above example we are fetching records from the user table, but suppose if it is not found then we need to raise an Exception that is UserNotFoundException(“Desired error message”). By using orElseThrow() it becomes easier to throw an exception when the required result is not there.
Java 9 added some new methods to the Optional class:
or() If a value is present, returns an
Optional
describing the value, otherwise returns anOptional
produced by the supplying function. — from the doc.ifPresentOrElse() If a value is present, performs the given action with the value, otherwise performs the given empty-based action. — from the doc.
stream() If a value is present, returns a sequential
Stream
containing only that value, otherwise returns an emptyStream
. — from the doc.
I hope you found this helpful, for any queries you can write to me on dalwadidarshan83@gmail.com.