Interface Try<Value>

Type Parameters:
Value - the type of the successful value
All Known Implementing Classes:
Try.Failure, Try.Success

@NullMarked public sealed interface Try<Value> permits Try.Success<Value>, Try.Failure<Value>
A monadic type that represents a computation that may either result in a value (Try.Success) or throw an exception (Try.Failure).

This interface is NullMarked: all methods return non-null values by default. The sole exception is getOrNull(), which may return null for two distinct reasons:

  1. This instance is a Try.Failure — no value is present.
  2. This instance is a Try.Success whose value is null, as produced by Try.run(...) which yields Success(null) on a successful void side-effect.

Success(null) is a valid and intentional state. Callers that need to distinguish "succeeded with null" from "failed" should use isSuccess(), fold(), or get() rather than getOrNull().

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Interface
    Description
    static interface 
    Functional interface for runnables that can throw checked exceptions.
    static interface 
    A functional interface representing a supplier that can produce a value and may throw a checked exception.
    static final record 
    Represents a computational failure within a context that implements the Try interface.
    static final record 
    Represents a successful computation result within the Try monad pattern.
  • Method Summary

    Modifier and Type
    Method
    Description
    static <V> Try<V>
    Creates a Try instance representing a failure with the given cause.
    default Try<Value>
    filter(Predicate<? super Value> predicate)
    Filters the Try based on the given predicate.
    default Try<Value>
    filter(Predicate<? super Value> predicate, Function<? super Value, ? extends Throwable> errorFn)
    Filters this Try using a predicate and a contextual error function that receives the value that failed the test.
    default Try<Value>
    filter(Predicate<? super Value> predicate, Supplier<? extends Throwable> throwableSupplier)
    Filters the Try based on the given predicate.
    default <NewValue> Try<NewValue>
    flatMap(Function<? super Value, Try<NewValue>> mapper)
    Applies the provided mapping function to the value contained within this `Try` instance if it represents a successful outcome.
    default <Folded> Folded
    fold(Function<? super Value, ? extends Folded> onSuccess, Function<? super Throwable, ? extends Folded> onFailure)
    Folds the current Try instance into a single value by applying one of two provided functions.
    static <V> Try<V>
    fromOption(Option<? extends V> opt, Supplier<? extends Throwable> exceptionSupplier)
    Converts an Option to a Try.
    static <V> Try<V>
    fromResult(Result<V, ? extends Throwable> result)
    Converts a Result into a Try instance.
    default Value
    get()
    Retrieves the value encapsulated in this instance if it represents a success.
    default Throwable
    Retrieves the cause of failure if the instance represents a failed state.
    default Value
    getOrElse(Value fallback)
    Returns the value if this instance is a Success, or the specified fallback value if it is a Failure.
    default Value
    getOrElseGet(Supplier<? extends Value> fallbackSupplier)
    Returns the value of this Try if it is a Success, or retrieves a fallback value using the provided fallbackSupplier if it is a Failure.
    default @Nullable Value
    Returns the value of this Try if it is a Success, or null if it is a Failure.
    default Value
    Returns the successful value if this instance is a Success, or throws an exception if this instance is a Failure.
    default Value
    getOrThrow(Function<? super Throwable, ? extends RuntimeException> exceptionMapper)
    Returns the value if this instance is a Success, or throws the exception provided by the exceptionMapper if this instance is a Failure.
    default boolean
    Determines if the current instance represents a failure state.
    default boolean
    Determines if the current instance represents a successful state.
    default <NewValue> Try<NewValue>
    map(Function<? super Value, ? extends NewValue> mapper)
    Transforms the value held by this instance using the provided mapping function.
    default Try<Value>
    mapFailure(Function<? super Throwable, ? extends Throwable> mapper)
    Transforms the failure cause using the given function, leaving a Success unchanged.
    static <V> Try<V>
    of(Try.CheckedSupplier<? extends V> supplier)
    Creates a Try instance by executing the given CheckedSupplier.
    default Try<Value>
    onFailure(Consumer<? super Throwable> action)
    Executes a specified action if this instance represents a failure.
    default Try<Value>
    onSuccess(Consumer<? super Value> action)
    Performs the given action if the current instance represents a successful outcome.
    default Try<Value>
    recover(Function<? super Throwable, ? extends Value> recoverFn)
    Recovers from a failure by applying a recovery function to the underlying throwable.
    default Try<Value>
    recoverWith(Function<? super Throwable, Try<Value>> recoverFn)
    Recovers from a failure by applying the given recovery function to the cause of the failure.
    static Try<Void>
    Executes the provided CheckedRunnable and returns a Try instance representing the outcome of the execution.
    static <V> Try<List<V>>
    sequence(Iterable<Try<V>> tries)
    Transforms an iterable of Try<V> into a single Try<List<V>>.
    static <V> Try<List<V>>
    sequence(Stream<Try<V>> tries)
    Transforms a stream of Try<V> into a single Try<List<V>>.
    default Stream<Value>
    Returns a single-element Stream containing the success value, or an empty stream on failure.
    static <V> Try<V>
    success(V value)
    Creates a successful Try instance containing the provided value.
    default Option<Value>
    Converts the current instance to an Option.
    Converts the current Try instance into a Result representation.
    default <E> Result<Value,E>
    toResult(Function<? super Throwable, ? extends E> errorMapper)
    Converts this Try into a Result<Value, E> using a custom error mapper.
    static <A,B> Try<List<B>>
    traverse(Iterable<A> values, Function<? super A, Try<B>> mapper)
    Maps each element of an iterable through mapper and collects the results into a Try<List<B>>.
    static <A,B> Try<List<B>>
    traverse(Stream<A> values, Function<? super A, Try<B>> mapper)
    Maps each element of a stream through mapper and collects the results into a Try<List<B>>.
  • Method Details

    • success

      static <V> Try<V> success(V value)
      Creates a successful Try instance containing the provided value.
      Type Parameters:
      V - the type of the value contained in the Try instance
      Parameters:
      value - the value to be wrapped in a successful Try instance
      Returns:
      a Try instance representing a successful computation containing the given value
    • failure

      static <V> Try<V> failure(Throwable cause)
      Creates a Try instance representing a failure with the given cause.
      Type Parameters:
      V - the type of the value that would have been returned in case of success
      Parameters:
      cause - the throwable that caused the failure; must not be null
      Returns:
      a Try instance representing the failure
    • of

      static <V> Try<V> of(Try.CheckedSupplier<? extends V> supplier)
      Creates a Try instance by executing the given CheckedSupplier. If the supplier executes successfully, a Try containing the result is returned. If an exception is thrown during execution, a Try containing the throwable is returned.
      Type Parameters:
      V - the type of the result supplied by the CheckedSupplier
      Parameters:
      supplier - the CheckedSupplier to execute
      Returns:
      a Try instance representing either a success with the supplied value or a failure with the thrown exception
    • run

      static Try<Void> run(Try.CheckedRunnable runnable)
      Executes the provided CheckedRunnable and returns a Try instance representing the outcome of the execution.

      Note on null value: On success the returned Try<Void> wraps null as its value (since Void has no instances). This means that converting the result via toOption() will always return Option.none() — use isSuccess() or fold() instead to observe the outcome of a run() call.

      Parameters:
      runnable - the CheckedRunnable to be executed
      Returns:
      a Try<Void> representing the success or failure of the execution. On success, its value is null; on failure, it contains the thrown exception.
    • isSuccess

      default boolean isSuccess()
      Determines if the current instance represents a successful state.
      Returns:
      true if the current instance is of type Success, false otherwise
    • isFailure

      default boolean isFailure()
      Determines if the current instance represents a failure state.
      Returns:
      true if the current instance is of type Failure, otherwise false.
    • get

      default Value get()
      Retrieves the value encapsulated in this instance if it represents a success. Throws a NoSuchElementException if this instance represents a failure.
      Returns:
      the value of this instance if it is a success
      Throws:
      NoSuchElementException - if this instance is a failure
    • getCause

      default Throwable getCause()
      Retrieves the cause of failure if the instance represents a failed state. For a successful state, this method throws a NoSuchElementException.
      Returns:
      the throwable cause of the failure if the instance is a Failure
      Throws:
      NoSuchElementException - if the instance is a Success as there is no cause
    • map

      default <NewValue> Try<NewValue> map(Function<? super Value, ? extends NewValue> mapper)
      Transforms the value held by this instance using the provided mapping function. If this instance represents a successful result, the mapping function is applied to its value. If this instance represents a failure, the failure is propagated.
      Type Parameters:
      NewValue - the type of the resulting value after applying the mapping function
      Parameters:
      mapper - the function to apply to the value if this instance represents a success
      Returns:
      a new instance of Try containing the mapped value if successful, or the original failure if unsuccessful
    • flatMap

      default <NewValue> Try<NewValue> flatMap(Function<? super Value, Try<NewValue>> mapper)
      Applies the provided mapping function to the value contained within this `Try` instance if it represents a successful outcome. The mapping function may produce a new `Try` instance representing either success or failure. If this instance is already a failure, it will return a failure with the same cause.
      Type Parameters:
      NewValue - the type of the result contained in the new `Try` instance
      Parameters:
      mapper - the mapping function to apply to the value, which produces a `Try` instance
      Returns:
      a new `Try` instance produced by applying the mapping function to the value, or a failure if either this instance is a failure or the function throws an exception
    • onSuccess

      default Try<Value> onSuccess(Consumer<? super Value> action)
      Performs the given action if the current instance represents a successful outcome.
      Parameters:
      action - a Consumer to be executed with the value of a successful outcome
      Returns:
      the current Try instance
    • onFailure

      default Try<Value> onFailure(Consumer<? super Throwable> action)
      Executes a specified action if this instance represents a failure.
      Parameters:
      action - the action to be executed, accepting the throwable cause of the failure
      Returns:
      the current instance of Try<Value>
    • recover

      default Try<Value> recover(Function<? super Throwable, ? extends Value> recoverFn)
      Recovers from a failure by applying a recovery function to the underlying throwable. If the current instance represents a success, it is returned as is. Otherwise, the recovery function is applied to the cause of the failure to produce a new success value. If the recovery function itself throws an exception, the method returns a new failure wrapping the thrown exception.
      Parameters:
      recoverFn - the recovery function to apply in case of failure, accepting the throwable cause of the failure and producing a new value
      Returns:
      a Try instance representing either the original success, a new success generated by applying the recovery function, or a new failure resulting from an exception thrown by the recovery function
    • recoverWith

      default Try<Value> recoverWith(Function<? super Throwable, Try<Value>> recoverFn)
      Recovers from a failure by applying the given recovery function to the cause of the failure.
      Parameters:
      recoverFn - the function that takes a throwable and returns a new Try instance for recovery. It is applied only in case of a failure.
      Returns:
      the original success instance if this is a success, or the result of the recovery function if this is a failure.
    • getOrElse

      default Value getOrElse(Value fallback)
      Returns the value if this instance is a Success, or the specified fallback value if it is a Failure.
      Parameters:
      fallback - the value to return if this instance is a Failure.
      Returns:
      the value of this instance if it is a Success, or the specified fallback value if it is a Failure.
    • getOrElseGet

      default Value getOrElseGet(Supplier<? extends Value> fallbackSupplier)
      Returns the value of this Try if it is a Success, or retrieves a fallback value using the provided fallbackSupplier if it is a Failure.
      Parameters:
      fallbackSupplier - a Supplier that provides an alternative value to return if this Try is a Failure.
      Returns:
      the value of this Try if it is a Success, or the value supplied by fallbackSupplier if it is a Failure.
    • getOrNull

      default @Nullable Value getOrNull()
      Returns the value of this Try if it is a Success, or null if it is a Failure.
      Returns:
      the successful value if this Try is a Success, or null if it is a Failure.
    • getOrThrow

      default Value getOrThrow() throws Exception
      Returns the successful value if this instance is a Success, or throws an exception if this instance is a Failure.
      Returns:
      the successful value of this Try if it is a Success.
      Throws:
      Exception - if this Try is a Failure and the failure cause is an Exception.
      RuntimeException - if this Try is a Failure and the failure cause is not an Exception.
    • getOrThrow

      default Value getOrThrow(Function<? super Throwable, ? extends RuntimeException> exceptionMapper)
      Returns the value if this instance is a Success, or throws the exception provided by the exceptionMapper if this instance is a Failure.
      Parameters:
      exceptionMapper - a function to map the failure cause (Throwable) to a RuntimeException that will be thrown.
      Returns:
      the value if this is a Success.
      Throws:
      RuntimeException - if this is a Failure and the exceptionMapper is invoked.
    • fold

      default <Folded> Folded fold(Function<? super Value, ? extends Folded> onSuccess, Function<? super Throwable, ? extends Folded> onFailure)
      Folds the current Try instance into a single value by applying one of two provided functions. If this Try is a Success, the onSuccess function is applied to the value. If this Try is a Failure, the onFailure function is applied to the cause.
      Type Parameters:
      Folded - the type of the result after applying one of the functions
      Parameters:
      onSuccess - a function to apply to the value if this Try is a Success
      onFailure - a function to apply to the cause if this Try is a Failure
      Returns:
      the result of applying the appropriate function based on the state of this Try
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate)
      Filters the Try based on the given predicate. If this is a Success and the predicate evaluates to true, the result is this Try instance. If the predicate evaluates to false, a Failure is returned using an IllegalArgumentException. If this is already a Failure, the result remains unchanged.

      On the Success path, if predicate is null or throws, a Failure(NullPointerException) or Failure(exception) is returned rather than propagating the error. An existing Failure is returned unchanged without evaluating the predicate, consistent with the Try philosophy of capturing throwables as values. See also filter(Predicate, Supplier) and filter(Predicate, java.util.function.Function).

      Parameters:
      predicate - the condition to evaluate for the value if this is a Success
      Returns:
      a Success if the predicate evaluates to true, or a Failure otherwise
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate, Supplier<? extends Throwable> throwableSupplier)
      Filters the Try based on the given predicate. If this is a Success and the predicate evaluates to true, the result is this Try instance. If the predicate evaluates to false, a Failure is returned using the provided throwable supplier. If this is already a Failure, the result remains unchanged.

      On the Success path, if predicate or throwableSupplier is null, or if either throws, a Failure wrapping the throwable is returned rather than propagating the error. throwableSupplier is only invoked when the predicate evaluates to false. An existing Failure is returned unchanged without evaluating the predicate or the supplier, consistent with the Try philosophy of capturing throwables as values. See also filter(Predicate) and filter(Predicate, java.util.function.Function).

      Parameters:
      predicate - the condition to evaluate for the value if this is a Success
      throwableSupplier - a supplier to provide the throwable for the Failure if the predicate evaluates to false
      Returns:
      a Success if the predicate evaluates to true, or a Failure otherwise
    • filter

      default Try<Value> filter(Predicate<? super Value> predicate, Function<? super Value, ? extends Throwable> errorFn)
      Filters this Try using a predicate and a contextual error function that receives the value that failed the test. If this is a Failure, it is returned unchanged. If this is a Success and the predicate returns false, a Failure is returned with the throwable produced by errorFn applied to the value.

      Unlike filter(Predicate, Supplier), the error function can produce a message that includes the offending value:

      
       Try.of(() -> parseAge(input))
          .filter(age -> age >= 0, age -> new IllegalArgumentException("negative age: " + age));
       

      On the Success path, if predicate throws, the exception is captured and returned as a Failure; if errorFn returns null, a Failure(NullPointerException) is returned rather than propagating the NPE. errorFn is only invoked when the predicate evaluates to false. Note that a null predicate or errorFn is detected eagerly and does throw NullPointerException before any value is tested, regardless of whether this instance is a Success or Failure. See also filter(Predicate) and filter(Predicate, Supplier).

      Parameters:
      predicate - the condition to test the value; must not be null
      errorFn - a function that produces the throwable when the predicate fails; must not be null; if it returns null, a Failure(NullPointerException) is returned
      Returns:
      this instance if the predicate holds or this is already a Failure; otherwise a new Failure produced by errorFn
      Throws:
      NullPointerException - if predicate or errorFn is null
    • toResult

      default Result<Value, Throwable> toResult()
      Converts the current Try instance into a Result representation. If this Try is a Success, the resulting Result will be "ok" with the successful value. If this Try is a Failure, the resulting Result will be "err" with the failure cause.
      Returns:
      a Result instance where the success value is mapped to "ok" and the failure cause is mapped to "err".
    • toResult

      default <E> Result<Value,E> toResult(Function<? super Throwable, ? extends E> errorMapper)
      Converts this Try into a Result<Value, E> using a custom error mapper. If this is a Success, returns Ok with the same value. If this is a Failure, applies errorMapper to the cause and returns Err.

      This overload is preferred over toResult() when a typed error is needed:

      
       Result<Config, String> r = Try.of(this::loadConfig)
           .toResult(e -> "load failed: " + e.getMessage());
       
      Type Parameters:
      E - the error type of the resulting Result
      Parameters:
      errorMapper - a function that maps the failure cause to the error value; must not return null
      Returns:
      Ok(value) on success, or Err(errorMapper.apply(cause)) on failure
      Throws:
      NullPointerException - if errorMapper is null or returns null
    • fromResult

      static <V> Try<V> fromResult(Result<V, ? extends Throwable> result)
      Converts a Result into a Try instance. If the Result is successful (contains a value), a successful Try is returned. If the Result contains an error, a failed Try is returned with the corresponding cause.
      Type Parameters:
      V - the type of the successful value
      Parameters:
      result - the Result to convert into a Try
      Returns:
      a Try representing either the successful value or the failure cause contained in the Result
    • mapFailure

      default Try<Value> mapFailure(Function<? super Throwable, ? extends Throwable> mapper)
      Transforms the failure cause using the given function, leaving a Success unchanged. If this is a Failure and mapper itself throws, the thrown exception becomes the new cause (mirroring the behaviour of map(java.util.function.Function<? super Value, ? extends NewValue>) on the success channel).

      Useful for wrapping low-level exceptions into domain exceptions:

      
       Try.of(db::query)
          .mapFailure(e -> new RepositoryException("query failed", e));
       
      Parameters:
      mapper - a function that maps the current cause to a new Throwable; must not return null
      Returns:
      this instance if Success, or a new Failure with the mapped cause; if mapper returns null or throws, the exception is wrapped as a new Failure
      Throws:
      NullPointerException - if mapper itself is null
    • stream

      default Stream<Value> stream()
      Returns a single-element Stream containing the success value, or an empty stream on failure. Mirrors Option.stream() for consistency.
      • Success(v) → Stream.of(v)
      • Failure → Stream.empty()
      Returns:
      a stream containing the value if this is a Success, or an empty stream otherwise
    • toOption

      default Option<Value> toOption()
      Converts the current instance to an Option. If the instance is a Success, wraps its value in an Option. If the instance is a Failure, returns an empty Option.
      Returns:
      an Option containing the value if the instance is a Success, or an empty Option if the instance is a Failure.
    • fromOption

      static <V> Try<V> fromOption(Option<? extends V> opt, Supplier<? extends Throwable> exceptionSupplier)
      Converts an Option to a Try. If the Option contains a value, a successful Try is returned with that value. Otherwise, a failed Try is created using the supplied exception.
      Type Parameters:
      V - the type of the value contained in the Option.
      Parameters:
      opt - the Option to be converted into a Try, must not be null.
      exceptionSupplier - the supplier of the exception to be used when the Option is empty, must not be null.
      Returns:
      a Try representing either a success containing the value of the Option, or a failure containing the exception provided by the supplier.
    • sequence

      static <V> Try<List<V>> sequence(Iterable<Try<V>> tries)
      Transforms an iterable of Try<V> into a single Try<List<V>>. If any element is a Failure, that failure is returned immediately (fail-fast). If all elements are Success, returns Success containing an unmodifiable list of values in encounter order.
      Type Parameters:
      V - the value type
      Parameters:
      tries - the iterable of Try values; must not be null and must not contain null elements
      Returns:
      Success(List<V>) if all elements succeed, or the first Failure encountered
      Throws:
      NullPointerException - if tries is null or contains a null element
    • sequence

      static <V> Try<List<V>> sequence(Stream<Try<V>> tries)
      Transforms a stream of Try<V> into a single Try<List<V>>. If any element is a Failure, that failure is returned immediately (fail-fast) and the stream is closed. If all elements are Success, returns Success containing an unmodifiable list of values in encounter order.
      Type Parameters:
      V - the value type
      Parameters:
      tries - the stream of Try values; must not be null and must not contain null elements
      Returns:
      Success(List<V>) if all elements succeed, or the first Failure encountered
      Throws:
      NullPointerException - if tries is null or contains a null element
    • traverse

      static <A,B> Try<List<B>> traverse(Iterable<A> values, Function<? super A, Try<B>> mapper)
      Maps each element of an iterable through mapper and collects the results into a Try<List<B>>. Fails fast on the first Failure returned by the mapper.
      Type Parameters:
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the iterable of input values; must not be null
      mapper - a function that maps each value to a Try; must not be null and must not return null
      Returns:
      Success(List<B>) if all mappings succeed, or the first Failure produced by the mapper
      Throws:
      NullPointerException - if values or mapper is null, or if the mapper returns null
    • traverse

      static <A,B> Try<List<B>> traverse(Stream<A> values, Function<? super A, Try<B>> mapper)
      Maps each element of a stream through mapper and collects the results into a Try<List<B>>. Fails fast on the first Failure returned by the mapper; the stream is closed in all cases.
      Type Parameters:
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the stream of input values; must not be null
      mapper - a function that maps each value to a Try; must not be null and must not return null
      Returns:
      Success(List<B>) if all mappings succeed, or the first Failure produced by the mapper
      Throws:
      NullPointerException - if values or mapper is null, or if the mapper returns null