0

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.

Pardha.Saradhi
  • 468
  • 1
  • 10
  • 27
  • Doesn't seem to have anything to do with the exception. Use `map()` instead of `flatMap()`. `getOrders()` returns a collection. `flatMap()` is for mappings that return an optional already. See [this question about the difference between Optional.flatmap and Optional.map](https://stackoverflow.com/questions/30864583/java-8-difference-between-optional-flatmap-and-optional-map). – Malte Hartwig Dec 06 '17 at 08:10
  • 1
    Now that you have updated your question, it is a duplicate for this: [How can I throw CHECKED exceptions from inside Java 8 streams? (Not wrapping it into unchecked exceptions)](https://stackoverflow.com/questions/27644361/how-can-i-throw-checked-exceptions-from-inside-java-8-streams-not-wrapping-it) – Malte Hartwig Dec 06 '17 at 12:52

0 Answers0