1

I know how to deal with exceptions in functional interfaces, but i have to move exception outside my lambda. (main should throw IOExc)

public static void main(String[] args) throws IOException {
    Function<String,List<String>> flines = f->{
//reading from input stream, but i cant use try catch
    }
}

My new interface has to inherit from java.util.function. Any ideas how to do it? Smth like this doesnt work well

 public interface MyFunction<T,R> extends Function<T,R> {


@Override
default R apply(T t) {
    try {
    return applyThrows(t);
    }catch (Exception e){
        throw new RuntimeException(e);
    }
}

R applyThrows (T t) throws IOException;
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Possible duplicate of [Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?](https://stackoverflow.com/questions/14039995/java-8-mandatory-checked-exceptions-handling-in-lambda-expressions-why-mandato) – Karol Dowbecki Nov 05 '18 at 20:22
  • 1
    Why should main throw an IOException? That seems like an completely artificial requirement to me. Anyway, all you can do is catch the runtime exception, and throw an IOException (i.e. do the inverse of what you're doing inside the function). – JB Nizet Nov 05 '18 at 20:23
  • @JBNizet you are right, just exercise in school. I can't swap them. Apply can't throws – Kamil Bielecki Nov 05 '18 at 21:04
  • I never told you to swap anything. I told you to catch the runtime exception that is thrown by your code, and to transform it back to a checked IOException.: `try { // some code throwing a runtime exception by calling your function } catch (RuntimeException e) { throw new IOException(e); }` – JB Nizet Nov 05 '18 at 21:06

2 Answers2

1

This can be done using jOOλ and its Sneaky.function taking a CheckedFunction, like below:

void sample() throws IOException {
    Function<String, List<String>> flines = Sneaky.function(this::applyThrows);
    flines.apply("");
}

List<String> applyThrows(String str) throws IOException {
    throw new IOException();
}

The Sneaky class let you throw the original checked exception but in a "sneaky" way.

If you don't want to depend on an external library, you can just copy CheckedException interface and write your own Sneaky.function based on the code of Unchecked.function and SeqUtils.sneakyThrow.

Tomasz Linkowski
  • 4,386
  • 23
  • 38
1

There are two aspects here:

  • As JB has commented, when you really have to get back a checked exception, then your lambda can wrap that into a runtime exception, and the outer code can catch that and unwrap the checked exception and rethrow that.
  • But then, it is not a good idea to force the language into constructs just because you can. If the core design point is to deal with IO, and you thus have the need to deal with IOExceptions, then the correct way would be to not use lambdas here!
GhostCat
  • 137,827
  • 25
  • 176
  • 248