javaoption-type

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());

Solution

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

    So we have 2 possibilities here.

    isExist = true or isExist = false;
    

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

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

    orElseThrow only throws exception when the optional variable is empty, that means, when isExist = true. If isExist = false, nothing happens. You can see the below signature to understand the basic concept of orElseThrow ...

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