0 votes
1 view
in Java by (10.2k points)

I have a problem trying out the Lambda expressions of Java 8. Usually it works fine, but now I have methods that throw IOException's. It's best if you look at the following code:

class Bank{

    ....

    public Set<String> getActiveAccountNumbers() throws IOException {

        Stream<Account> s =  accounts.values().stream();

        s = s.filter(a -> a.isActive());

        Stream<String> ss = s.map(a -> a.getNumber());

        return ss.collect(Collectors.toSet());

    }

    ....

}

interface Account{

    ....

    boolean isActive() throws IOException;

    String getNumber() throws IOException;

    ....

}

The problem is, it doesn't compile, because I have to catch the possible exceptions of the isActive- and the getNumber-Methods. But even if I explicitly use a try-catch-Block like below, it still doesn't compile because I don't catch the Exception. So either there is a bug in JDK, or I don't know how to catch these Exceptions.

class Bank{

    ....

    //Doesn't compile either

    public Set<String> getActiveAccountNumbers() throws IOException {

        try{

            Stream<Account> s =  accounts.values().stream();

            s = s.filter(a -> a.isActive());

            Stream<String> ss = s.map(a -> a.getNumber());

            return ss.collect(Collectors.toSet());

        }catch(IOException ex){

        }

    }

    ....

}

How can I get it work? Can someone hint me to the right solution?

1 Answer

0 votes
by (46.1k points)

Use #propagate() method. Sample non-Guava implementation:

public class Throwables {

    public interface ExceptionWrapper<E> {

        E wrap(Exception e);

    }

    public static <T> T propagate(Callable<T> callable) throws RuntimeException {

        return propagate(callable, RuntimeException::new);

    }

    public static <T, E extends Throwable> T propagate(Callable<T> callable, ExceptionWrapper<E> wrapper) throws E {

        try {

            return callable.call();

        } catch (RuntimeException e) {

            throw e;

        } catch (Exception e) {

            throw wrapper.wrap(e);

        }

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...