Class Try<T>

java.lang.Object
nva.commons.core.attempt.Try<T>
Type Parameters:
T - the contained object.
Direct Known Subclasses:
Failure, Success

public abstract class Try<T> extends Object
Utility class for handling checked exceptions in map functions. Check tests for examples
  • Field Details

  • Constructor Details

    • Try

      public Try()
  • Method Details

    • of

      public static <T> Try<T> of(T input)
    • attempt

      public static <S> Try<S> attempt(Callable<S> action)
      A wrapper for actions that throw checked Exceptions. See: "https://www.oreilly.com/content/handling-checked-exceptions-in-java-streams" Try to perform the action. Any exception will be enclosed in a Failure.
      Type Parameters:
      S - the resulting object
      Parameters:
      action - a Callable action that throws or does not throw a checked Exception
      Returns:
      a new Try instance
    • attempt

      public static <T, R, E extends Exception> Function<T,Try<R>> attempt(FunctionWithException<T,R,E> fe)
      A wrapper for functions that throw checked Exceptions. See: "https://www.oreilly.com/content/handling-checked-exceptions-in-java-streams" Try to perform the action. Any exception will be enclosed in a Failure.
      Type Parameters:
      T - the type of the argument of the function.
      R - the type of the result of the function
      E - the type of the thrown Exception
      Parameters:
      fe - a FunctionWithException function that throws or does not throw a checked Exception
      Returns:
      a new Try instance
    • stream

      public abstract Stream<T> stream()
    • isSuccess

      public abstract boolean isSuccess()
    • get

      public abstract T get()
    • getException

      public abstract Exception getException()
    • isFailure

      public final boolean isFailure()
    • map

      public abstract <S, E extends Exception> Try<S> map(FunctionWithException<T,S,E> action)
    • flatMap

      public abstract <S, E extends Exception> Try<S> flatMap(FunctionWithException<T,Try<S>,E> action)
    • forEach

      public abstract <E extends Exception> Try<Void> forEach(ConsumerWithException<T,E> consumer)
    • orElseThrow

      public abstract <E extends Exception> T orElseThrow(Function<Failure<T>,E> action) throws E
      Throws:
      E extends Exception
    • orElseThrow

      public T orElseThrow(RuntimeException e)
    • orElseThrow

      public abstract T orElseThrow()
    • orElse

      public abstract <E extends Exception> T orElse(FunctionWithException<Failure<T>,T,E> action) throws E
      Throws:
      E extends Exception
    • toOptional

      public abstract <E extends Exception> Optional<T> toOptional(ConsumerWithException<Failure<T>,E> action) throws E
      Throws:
      E extends Exception
    • toOptional

      public abstract Optional<T> toOptional()
    • or

      public abstract Try<T> or(Callable<T> action)