I have tried implementing Optional from JAVA in the below code. getOrders() method throws a KException.
@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
List<Order> orders=null;
try {
Optional<KConnect> connection = connector.getConnection(authDTO);
if (connection.isPresent()) {
orders = connection.get().getOrders();
}
}catch (KException e){
throw new MyException(e.message,e.code);
}
return Optional.ofNullable(orders);
}
I tried to remove the isPresent() check and replace it with flatmap.
@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
return connector.getConnection(authDTO).map(p -> {
try {
return p.getOrders();
} catch (KException e) {
throw new MyException(e.message,e.code); // [EXP LINE]
}
});
}
In this case I am not able to catch KException and convert it to MyException. My code won't compile.
unreported exception com.myproject.exception.MyException; must be caught or declared to be thrown
1st snippet works perfectly fine for me. Is there a better way to do this? Please suggest.
Edit: This does not change if I make it map instead of flatmap.
The exact problem is that IntelliJ is saying unhandled exception: com.myproject.exception.MyException
at [EXP LINE] even though the method has throws MyExpception present.