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 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;
}
}