Bastian Bastian - 1 year ago 98
Java Question

Java 8: How do I work with exception throwing methods in streams?

Suppose I have a class and a method

class A {
void foo() throws Exception() {

Now I would like to call foo for each instance of
delivered by a stream like:

void bar() throws Exception {
Stream<A> as = ...
as.forEach(a ->;

Question: How do I properly handle the exception? The code does not compile on my machine because I do not handle the possible exceptions that can be thrown by foo(). The
throws Exception
seems to be useless here. Why is that?

Answer Source

You need to wrap your method call into another one, where you do not throw checked exceptions. You can still throw anything that is a subclass of RuntimeException.

A normal wrapping idiom is something like:

private void safeFoo(final A a) {
    try {;
    } catch (Exception ex) {
        throw new RuntimeException(ex);

(Supertype exception Exception is only used as example, never try to catch it yourself)

Then you can call it with: as.forEach(this::safeFoo).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download