Class Try<T>

  • Type Parameters:
    T - Value type of a successful computation
    All Implemented Interfaces:
    Iterable<T>, java.io.Serializable, java.lang.Iterable<T>

    public abstract class Try<T>
    extends java.lang.Object
    implements Iterable<T>, java.io.Serializable
    The Try control gives us the ability to write safe code without focusing on try-catch blocks in the presence of exceptions.

    A real-world use-case is to defer error handling and recovery to outer applications layers. With Try, we achieve this by capturing the error state of a computation and passing it around.

    Try has one of two states, Success and Failure. A Success wraps the value of a given computation, a Failure wraps an exception that occurred during the computation.

    The following exceptions are considered to be fatal/non-recoverable and will be re-thrown:

    • LinkageError
    • ThreadDeath
    • VirtualMachineError (i.e. OutOfMemoryError or StackOverflowError)

    Creation

    Try is intended to be used as value which contains the result of a computation. For that purpose, of(Callable) is called. See also success(Object) and failure(Throwable).

    However, some use Try as syntactic sugar for try-catch blocks that only perform side-effects. For that purpose, run(CheckedRunnable) is called. This variant does not contain a value but is still able to observe, handle and recover an error state.

    Capturing exceptions

    Opposed to other types, higher-order functions that transform this type take checked functions, or more precisely, lambdas or method references that may throw checked exceptions.

    We intentionally do not provide alternate methods that take unchecked functions (like map vs mapTry). Instead we make it explicit on the API layer that exceptions are properly handled when transforming values. An exception will not escape the context of a Try in these cases.

    Another reason for not providing unchecked variants is that Vavr's higher-order functions always take the most general argument type. Checked functions that may throw Throwable are more general than unchecked functions because unchecked exceptions are restricted to throw runtime exceptions.

    Higher-order functions that return a concrete value, like getOrElseGet(Supplier) and fold(Function, Function), will not handle exceptions when calling function arguments. The parameter types make this clear.

    Transforming a Try

    Transformations that are focused on a successful state are: Transformations that are focused on a failed state are: More general transformations that take both states (success/failure) into account are:

    Handling the state of a Try

    Opposed to Java (see Optional.ifPresent(Consumer)), we are able to chain one or more of the following actions:

    Getting the value of a Try

    At some point, we might need to operate on the unwrapped value of a Try. These are our options to reduce a successful or failed state to a value:

    Try with resources

    It is also possible to use Try directly with AutoCloseable resources:
    
     final Try<T> calc = Try.of(() -> {
         try (final ac1 = someAutoCloseable1(); ...; final acn = someAutoCloseableN()) {
             return doSth(ac1, ..., acn);
         } finally {
             doSth();
         }
     });
     
    See Also:
    Serialized Form
    • Method Summary

      All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      <R,​A>
      R
      collect​(java.util.stream.Collector<? super T,​A,​R> collector)
      Collects the underlying value (if present) using the provided collector.
      abstract boolean equals​(java.lang.Object that)
      Checks if this Try is equal to the given object o.
      Try<java.lang.Throwable> failed()
      Inverts this Try.
      static <T> Try<T> failure​(java.lang.Throwable exception)
      Creates a Try.Failure that contains the given exception.
      Try<T> filter​(CheckedPredicate<? super T> predicate)
      Returns this if this is a Failure or this is a Success and the value satisfies the predicate.
      <U> Try<U> flatMap​(CheckedFunction<? super T,​? extends Try<? extends U>> mapper)
      FlatMaps the value of a Success or returns a Failure.
      <U> U fold​(java.util.function.Function<? super java.lang.Throwable,​? extends U> ifFailure, java.util.function.Function<? super T,​? extends U> ifSuccess)
      Folds either the Failure or the Success side of the Try value.
      abstract T get()
      Deprecated.
      Unsafe operation (but not marked for removal).
      abstract java.lang.Throwable getCause()
      Deprecated.
      Unsafe operation (but not marked for removal).
      T getOrElse​(T other)
      Returns the underlying value if present, otherwise other.
      T getOrElseGet​(java.util.function.Supplier<? extends T> supplier)
      Returns the underlying value if present, otherwise the result of other.get().
      <X extends java.lang.Throwable>
      T
      getOrElseThrow​(java.util.function.Function<? super java.lang.Throwable,​? extends X> exceptionProvider)
      Returns the underlying value if present, otherwise throws a user-specific exception.
      abstract int hashCode()
      Computes the hash of this Try.
      abstract boolean isFailure()
      Checks if this is a Failure.
      abstract boolean isSuccess()
      Checks if this is a Success.
      Iterator<T> iterator()
      Returns an Iterator that allows us to perform intermediate, sequential operations known from Vavr's collection library.
      <U> Try<U> map​(CheckedFunction<? super T,​? extends U> mapper)
      Runs the given checked function if this is a Try.Success, passing the result of the current expression to it.
      Try<T> mapFailure​(CheckedFunction<? super java.lang.Throwable,​? extends java.lang.Throwable> mapper)
      Maps the cause to a new exception if this is a Failure or returns this instance if this is a Success.
      static <T> Try<T> of​(java.util.concurrent.Callable<? extends T> callable)
      Creates a Try of a Callable.
      Try<T> onFailure​(java.util.function.Consumer<? super java.lang.Throwable> action)
      Consumes the cause if this is a Try.Failure.
      Try<T> onSuccess​(java.util.function.Consumer<? super T> action)
      Consumes the value if this is a Try.Success.
      Try<T> orElse​(java.util.concurrent.Callable<? extends Try<? extends T>> callable)
      Returns this Try in the case of a Success, otherwise other.call().
      <X extends java.lang.Throwable>
      Try<T>
      recover​(java.lang.Class<X> exceptionType, CheckedFunction<? super X,​? extends T> recoveryFunction)
      Returns this, if this is a Success or this is a Failure and the cause is not assignable from cause.getClass().
      <X extends java.lang.Throwable>
      Try<T>
      recoverWith​(java.lang.Class<X> exceptionType, CheckedFunction<? super X,​? extends Try<? extends T>> recoveryFunction)
      Returns this, if this is a Success or this is a Failure and the cause is not assignable from cause.getClass().
      static Try<java.lang.Void> run​(CheckedRunnable runnable)
      Runs a CheckedRunnable and captures any non-fatal exception in a Try.
      java.util.stream.Stream<T> stream()
      Converts this Try to a Stream.
      static <T> Try<T> success​(T value)
      Creates a Try.Success that contains the given value.
      <U> Either<U,​T> toEither​(java.util.function.Function<? super java.lang.Throwable,​? extends U> failureMapper)
      Converts this Try to an Either.
      Option<T> toOption()
      Converts this Try to an Option.
      java.util.Optional<T> toOptional()
      Converts this Try to an Optional.
      abstract java.lang.String toString()
      Returns a string representation of this Try.
      <U> Try<U> transform​(CheckedFunction<? super java.lang.Throwable,​? extends Try<? extends U>> ifFailure, CheckedFunction<? super T,​? extends Try<? extends U>> ifSuccess)
      Transforms this Try by applying either ifSuccess to this value or ifFailure to this cause.
      • Methods inherited from class java.lang.Object

        clone, finalize, getClass, notify, notifyAll, wait, wait, wait
      • Methods inherited from interface java.lang.Iterable

        forEach, spliterator
    • Method Detail

      • of

        public static <T> Try<T> of​(java.util.concurrent.Callable<? extends T> callable)
        Creates a Try of a Callable.
        Type Parameters:
        T - Component type
        Parameters:
        callable - A supplier that may throw a checked exception
        Returns:
        Success(callable.call()) if no exception occurs, otherwise Failure(cause) if a non-fatal error occurs calling callable.call().
        Throws:
        java.lang.Error - if the cause of the Try.Failure is fatal, i.e. non-recoverable
      • run

        public static Try<java.lang.Void> run​(CheckedRunnable runnable)
        Runs a CheckedRunnable and captures any non-fatal exception in a Try.

        Because running a unit of work is all about performing side-effects rather than returning a value, a Try<Void> is created.

        Parameters:
        runnable - A checked runnable, i.e. a runnable that may throw a checked exception.
        Returns:
        Success(null) if no exception occurs, otherwise Failure(throwable) if an exception occurs calling runnable.run().
        Throws:
        java.lang.Error - if the cause of the Try.Failure is fatal, i.e. non-recoverable
      • success

        public static <T> Try<T> success​(T value)
        Creates a Try.Success that contains the given value. Shortcut for new Success<>(value).
        Type Parameters:
        T - Type of the given value.
        Parameters:
        value - A value.
        Returns:
        A new Success.
      • failure

        public static <T> Try<T> failure​(java.lang.Throwable exception)
        Creates a Try.Failure that contains the given exception. Shortcut for new Failure<>(exception).
        Type Parameters:
        T - Component type of the Try.
        Parameters:
        exception - An exception.
        Returns:
        A new Failure.
        Throws:
        java.lang.Error - if the given exception is fatal, i.e. non-recoverable
      • collect

        public <R,​A> R collect​(java.util.stream.Collector<? super T,​A,​R> collector)
        Collects the underlying value (if present) using the provided collector.

        Shortcut for .stream().collect(collector).

        Type Parameters:
        A - the mutable accumulation type of the reduction operation
        R - the result type of the reduction operation
        Parameters:
        collector - Collector performing reduction
        Returns:
        the reduction result of type R
        Throws:
        java.lang.NullPointerException - if the given collector is null
      • failed

        public Try<java.lang.Throwable> failed()
        Inverts this Try.
        Returns:
        Success(throwable) if this is a Failure(throwable), otherwise a Failure(new UnsupportedOperationException("Success.failed()")) if this is a Success.
      • filter

        public Try<T> filter​(CheckedPredicate<? super T> predicate)
        Returns this if this is a Failure or this is a Success and the value satisfies the predicate.

        Returns a new Failure, if this is a Success and the value does not satisfy the Predicate or an exception occurs testing the predicate. The returned Failure wraps a NoSuchElementException instance.

        Parameters:
        predicate - A checked predicate
        Returns:
        a Try instance
        Throws:
        java.lang.NullPointerException - if predicate is null
      • flatMap

        public <U> Try<U> flatMap​(CheckedFunction<? super T,​? extends Try<? extends U>> mapper)
        FlatMaps the value of a Success or returns a Failure.
        Type Parameters:
        U - The new component type
        Parameters:
        mapper - A mapper
        Returns:
        a Try
        Throws:
        java.lang.NullPointerException - if mapper is null
      • fold

        public <U> U fold​(java.util.function.Function<? super java.lang.Throwable,​? extends U> ifFailure,
                          java.util.function.Function<? super T,​? extends U> ifSuccess)
        Folds either the Failure or the Success side of the Try value.
        Type Parameters:
        U - type of the folded value
        Parameters:
        ifFailure - maps the cause if this is a Failure
        ifSuccess - maps the value if this is a Success
        Returns:
        A value of type U
        Throws:
        java.lang.NullPointerException - if one of the given ifFailure or ifSuccess is null
      • getCause

        @Deprecated
        public abstract java.lang.Throwable getCause()
                                              throws java.lang.UnsupportedOperationException
        Deprecated.
        Unsafe operation (but not marked for removal). Use fold(Function, Function) instead. An alternative is onFailure(Consumer).
        Gets the cause if this is a Failure or throws if this is a Success.
        Returns:
        The cause if this is a Failure
        Throws:
        java.lang.UnsupportedOperationException - if this is a Success
      • getOrElse

        public T getOrElse​(T other)
        Returns the underlying value if present, otherwise other.
        Parameters:
        other - An alternative value.
        Returns:
        A value of type T
      • getOrElseGet

        public T getOrElseGet​(java.util.function.Supplier<? extends T> supplier)
        Returns the underlying value if present, otherwise the result of other.get().
        Parameters:
        supplier - A Supplier of an alternative value.
        Returns:
        A value of type T
        Throws:
        java.lang.NullPointerException - if the given other is null
      • getOrElseThrow

        public <X extends java.lang.Throwable> T getOrElseThrow​(java.util.function.Function<? super java.lang.Throwable,​? extends X> exceptionProvider)
                                                         throws X extends java.lang.Throwable
        Returns the underlying value if present, otherwise throws a user-specific exception.
        Type Parameters:
        X - exception type
        Parameters:
        exceptionProvider - provides a user-specific exception
        Returns:
        A value of type T
        Throws:
        X - if this is a Failure
        java.lang.NullPointerException - if the given exceptionProvider is null
        X extends java.lang.Throwable
      • isFailure

        public abstract boolean isFailure()
        Checks if this is a Failure.
        Returns:
        true, if this is a Failure, otherwise false, if this is a Success
      • isSuccess

        public abstract boolean isSuccess()
        Checks if this is a Success.
        Returns:
        true, if this is a Success, otherwise false, if this is a Failure
      • iterator

        public Iterator<T> iterator()
        Description copied from interface: Iterable
        Returns an Iterator that allows us to perform intermediate, sequential operations known from Vavr's collection library.
        Specified by:
        iterator in interface Iterable<T>
        Specified by:
        iterator in interface java.lang.Iterable<T>
        Returns:
        an Iterator instance. It is not necessarily a new instance, like that returned by Iterator.empty().
      • map

        public <U> Try<U> map​(CheckedFunction<? super T,​? extends U> mapper)
        Runs the given checked function if this is a Try.Success, passing the result of the current expression to it. If this expression is a Try.Failure then it'll return a new Try.Failure of type R with the original exception.

        The main use case is chaining checked functions using method references:

         
         Try.of(() -> 0)
            .map(x -> 1 / x); // division by zero
         
         
        Type Parameters:
        U - The new component type
        Parameters:
        mapper - A checked function
        Returns:
        a Try
        Throws:
        java.lang.NullPointerException - if mapper is null
      • mapFailure

        public Try<T> mapFailure​(CheckedFunction<? super java.lang.Throwable,​? extends java.lang.Throwable> mapper)
        Maps the cause to a new exception if this is a Failure or returns this instance if this is a Success.
        Parameters:
        mapper - A function that maps the cause of a failure to another exception.
        Returns:
        A new Try if this is a Failure, otherwise this.
        Throws:
        java.lang.NullPointerException - if the given mapper is null
      • onFailure

        public Try<T> onFailure​(java.util.function.Consumer<? super java.lang.Throwable> action)
        Consumes the cause if this is a Try.Failure.
        
         // (does not print anything)
         Try.success(1).onFailure(System.out::println);
        
         // prints "java.lang.Error"
         Try.failure(new Error()).onFailure(System.out::println);
         
        Parameters:
        action - An exception consumer
        Returns:
        this
        Throws:
        java.lang.NullPointerException - if action is null
      • onSuccess

        public Try<T> onSuccess​(java.util.function.Consumer<? super T> action)
        Consumes the value if this is a Try.Success.
        
         // prints "1"
         Try.success(1).onSuccess(System.out::println);
        
         // (does not print anything)
         Try.failure(new Error()).onSuccess(System.out::println);
         
        Parameters:
        action - A value consumer
        Returns:
        this
        Throws:
        java.lang.NullPointerException - if action is null
      • orElse

        public Try<T> orElse​(java.util.concurrent.Callable<? extends Try<? extends T>> callable)
        Returns this Try in the case of a Success, otherwise other.call().
        Parameters:
        callable - a Callable
        Returns:
        a Try instance
      • recover

        public <X extends java.lang.Throwable> Try<T> recover​(java.lang.Class<X> exceptionType,
                                                              CheckedFunction<? super X,​? extends T> recoveryFunction)
        Returns this, if this is a Success or this is a Failure and the cause is not assignable from cause.getClass().

        Otherwise tries to recover the exception of the failure with recoveryFunction.

        
         // = Success(13)
         Try.of(() -> 27/2).recover(ArithmeticException.class, x -> Integer.MAX_VALUE);
        
         // = Success(2147483647)
         Try.of(() -> 1/0)
            .recover(Error.class, x -> -1)
            .recover(ArithmeticException.class, x -> Integer.MAX_VALUE);
        
         // = Failure(java.lang.ArithmeticException: / by zero)
         Try.of(() -> 1/0).recover(Error.class, x -> Integer.MAX_VALUE);
         
        Type Parameters:
        X - Exception type
        Parameters:
        exceptionType - The specific exception type that should be handled
        recoveryFunction - A recovery function taking an exception of type X
        Returns:
        a Try instance
        Throws:
        java.lang.NullPointerException - if exception is null or recoveryFunction is null
      • recoverWith

        public <X extends java.lang.Throwable> Try<T> recoverWith​(java.lang.Class<X> exceptionType,
                                                                  CheckedFunction<? super X,​? extends Try<? extends T>> recoveryFunction)
        Returns this, if this is a Success or this is a Failure and the cause is not assignable from cause.getClass(). Otherwise tries to recover the exception of the failure with recoveryFunction which returns Try. If isFailure() returned by recoveryFunction function is true it means that recovery cannot take place due to some circumstances.
        
         // = Success(13)
         Try.of(() -> 27/2).recoverWith(ArithmeticException.class, x -> Try.success(Integer.MAX_VALUE));
        
         // = Success(2147483647)
         Try.of(() -> 1/0)
            .recoverWith(Error.class, x -> Try.success(-1))
            .recoverWith(ArithmeticException.class, x -> Try.success(Integer.MAX_VALUE));
        
         // = Failure(java.lang.ArithmeticException: / by zero)
         Try.of(() -> 1/0).recoverWith(Error.class, x -> Try.success(Integer.MAX_VALUE));
         
        Type Parameters:
        X - Exception type
        Parameters:
        exceptionType - The specific exception type that should be handled
        recoveryFunction - A recovery function taking an exception of type X and returning Try as a result of recovery. If Try is isSuccess() then recovery ends up successfully. Otherwise the function was not able to recover.
        Returns:
        a Try instance
        Throws:
        java.lang.NullPointerException - if exceptionType or recoveryFunction is null
        java.lang.Error - if the given recovery function recoveryFunction throws a fatal error
      • stream

        public java.util.stream.Stream<T> stream()
        Converts this Try to a Stream.
        Returns:
        Stream.of(get() if this is a success, otherwise Stream.empty()
      • toEither

        public <U> Either<U,​T> toEither​(java.util.function.Function<? super java.lang.Throwable,​? extends U> failureMapper)
        Converts this Try to an Either.
        Type Parameters:
        U - the left type of the Either
        Parameters:
        failureMapper - a failure mapper
        Returns:
        Either.right(get() if this is a success, otherwise Either.left(failureMapper.apply(getCause())
        Throws:
        java.lang.NullPointerException - if the given failureMapper is null
      • toOption

        public Option<T> toOption()
        Converts this Try to an Option.
        Returns:
        Option.some(get() if this is a success, otherwise Option.none()
      • toOptional

        public java.util.Optional<T> toOptional()
        Converts this Try to an Optional.
        Returns:
        Optional.ofNullable(get()) if this is a success, otherwise Optional.empty()
      • transform

        public <U> Try<U> transform​(CheckedFunction<? super java.lang.Throwable,​? extends Try<? extends U>> ifFailure,
                                    CheckedFunction<? super T,​? extends Try<? extends U>> ifSuccess)
        Transforms this Try by applying either ifSuccess to this value or ifFailure to this cause.
        Type Parameters:
        U - type of the transformed value
        Parameters:
        ifFailure - maps the cause if this is a Failure
        ifSuccess - maps the value if this is a Success
        Returns:
        A new Try instance
        Throws:
        java.lang.NullPointerException - if one of the given ifSuccess or ifFailure is null
      • equals

        public abstract boolean equals​(java.lang.Object that)
        Checks if this Try is equal to the given object o.
        Overrides:
        equals in class java.lang.Object
        Parameters:
        that - an object, may be null
        Returns:
        true, if this and that both are a success and the underlying values are equal or if this and that both are a failure and the underlying causes refer to the same object. Otherwise it returns false.
      • hashCode

        public abstract int hashCode()
        Computes the hash of this Try.
        Overrides:
        hashCode in class java.lang.Object
        Returns:
        31 + Objects.hashCode(get()) if this is a success, otherwise Objects.hashCode(getCause())
      • toString

        public abstract java.lang.String toString()
        Returns a string representation of this Try.
        Overrides:
        toString in class java.lang.Object
        Returns:
        "Success(" + get() + ")" if this is a success, otherwise "Failure(" + getCause() + ")"