Testing try / catch with a function in Java 8

I recently discovered that I wrote many blocks of the following form:

try {
    return Optional.of(thing.doSomething(arg));
} catch (Exception e) {
    System.out.println(e.getMessage());
    return Optional.empty();
}

This is necessary because some methods signal that they can throw exceptions, and Eclipse yells at me if I do not surround these methods with try / catch blocks.

So I wrote this:

public static <A, T> Optional<T> tryOpt (Function<A, T> f, A arg) {
    try {
        return Optional.of(f.apply(arg));
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return Optional.empty();
    }
}

So, any function I pass to tryOpt is enclosed in a try / catch block and executed safely, and its result is returned as optional. But Eclipse is still yelling at me for using it:

return tryOpt(
          ((x) -> thing.doSomething(x)),
          arg);

, - Eclipse / java, , try/catch? - , java, - ? , , Eclipse ?

+4
3

Function.apply , , , .

, , . (, java.util. *):

public static <A, T> Optional<T> tryOpt (Fn<A, T> f, A arg) {
    try {
        return Optional.of(f.apply(arg));
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return Optional.empty();
    }
}


public static interface Fn<A, T> {
      T apply(A a) throws Exception;
}
+4

, , .

Function<A,R> , , . , , , -

public interface SupplierWithException<R> {R get();}

:

return asOptional(() -> thing.doSomething(arg1, arg2, arg3));

, - ; asOptional, , (, ?). RuntimeException s, - RxJava, .

+2

, lambdas , , , , , .

, , - :

  @FunctionalInterface
  public interface FunctionThrowing<T, R>
  {
    R apply(T t) throws Exception;
  }


  public static <T, R> Function<T, R> wrapFunction(FunctionThrowing<T, R> function)
  {
    return a -> {
      try
      {
        return function.apply(a);
      } catch (Exception exception)
      {
        throw exception;
        return null;
      }
    };
  }

This basically wraps the function, returning a function that handles the checked exception and converts it into an unchecked exception, so you don't need to wrap each call in a block try/catch, but you still don't lose the ability to catch the exception (since it is not controlled).

+1
source

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


All Articles