Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Exception will be thrown from orElseThrow method in JAVA 8?

I have one field called isExist and it is either false or true in line #1.
based on this, in line#2 either Optional.empty() is executed or Optional.of(1) is getting executed but never Exception is thrown from orElseThrow method in line#2.

can anyone please explain when Exception will be thrown ? on which condition Exception will be thrown ?

line#1 final boolean isExist  = (user != null && CollectionUtils.isNotEmpty(user.getIds())
                && user.getIds().contains(id));

line#2 (isExist ? Optional.empty() : Optional.of(1)).orElseThrow(
                () -> new Exception());

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From line1, it will assign true/false to isExist variable.

So we have 2 possibility here.

isExist = true or isExist = false;

At line 2, the tertiary condition can be understand as:

Optional optional = null;
if(isExist){
   optional = Optional.empty();
}else{
   optional = Optional.of(1)
}
optional.orElseThrow(() -> new Exception());

orElseThrow only throw exception when optional variable is empty, it mean when isExist = true. If isExist = false, nothing happen.
You can see below signature to understand the basic concept of orElseThrow …

public void orElseThrow(Exception ex){
  if(!isPresent()){
     throw ex;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading