Lambda expression handling exception

I have a problem with a lambda expression. My code is:

public static void main(String[] args) {

    Function<String, String> lambda = path -> {
        String result = null;
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            String line;
            while ((line = br.readLine()) != null) {
                result = result + line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    };
}

Now I'm trying to make a code like this:

public static void main(String[] args) throws IOException {

    Function<String, String> lambda = path -> {
        String result = null;
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        while ((line = br.readLine()) != null) {
            result = result + line;
        }
        return result;
    };
}

Is it possible? I can only use java.util.function. I am trying to remove try catch from lambda, and my main method should catch this exception.

+4
source share
2 answers

The built-in class Functiondoes not allow you to throw thrown exceptions, as you can see from the method signature apply().

However, you can easily define your own @FunctionalInterface, which allows you to throw exceptions, for example:

@FunctionalInterface
public interface CheckedFunction<U,V> {
  public V apply(U u) throws Exception;
}

And make a lambdavariable a instead CheckedFunction.


, Function - , , RuntimeException s, :

Function<Foo,Bar> f = foo -> {
  try {
    return foo.methodThatCanThrow();
  } catch (RuntimeException e) {
    throw e;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
};

, , , .

+4

dimo414,

@FunctionalInterface
public interface CheckedFunction<U, V> {
    public V apply(U u) throws IOException;
}

, - :

CheckedFunction<String, String> lambda = path -> {
            try (BufferedReader br = new BufferedReader(new FileReader(path))) {
                return br.lines().collect(Collectors.joining());
            }
        };

try-with-resources BufferedRead stream API, .

, BufferedReader, Files! :

CheckedFunction<String, String> lambda = path -> Files.lines(Paths.get(path)).collect(Collectors.joining());
+2

Source: https://habr.com/ru/post/1659692/


All Articles