Interface Try<Value>
- Type Parameters:
Value- the type of the successful value
- All Known Implementing Classes:
Try.Failure,Try.Success
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:
- This instance is a
Try.Failure— no value is present. - This instance is a
Try.Successwhose value isnull, as produced byTry.run(...)which yieldsSuccess(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 ClassesModifier and TypeInterfaceDescriptionstatic interfaceFunctional interface for runnables that can throw checked exceptions.static interfaceA functional interface representing a supplier that can produce a value and may throw a checked exception.static final recordRepresents a computational failure within a context that implements theTryinterface.static final recordRepresents a successful computation result within the Try monad pattern. -
Method Summary
Modifier and TypeMethodDescriptionstatic <V> Try<V> Creates aTryinstance representing a failure with the given cause.Filters the Try based on the given predicate.Filters thisTryusing a predicate and a contextual error function that receives the value that failed the test.Filters the Try based on the given predicate.default <NewValue> Try<NewValue> Applies the provided mapping function to the value contained within this `Try` instance if it represents a successful outcome.default <Folded> Foldedfold(Function<? super Value, ? extends Folded> onSuccess, Function<? super Throwable, ? extends Folded> onFailure) Folds the currentTryinstance into a single value by applying one of two provided functions.static <V> Try<V> fromOption(Option<? extends V> opt, Supplier<? extends Throwable> exceptionSupplier) static <V> Try<V> fromResult(Result<V, ? extends Throwable> result) default Valueget()Retrieves the value encapsulated in this instance if it represents a success.default ThrowablegetCause()Retrieves the cause of failure if the instance represents a failed state.default ValueReturns the value if this instance is aSuccess, or the specified fallback value if it is aFailure.default ValuegetOrElseGet(Supplier<? extends Value> fallbackSupplier) Returns the value of thisTryif it is aSuccess, or retrieves a fallback value using the providedfallbackSupplierif it is aFailure.default @Nullable ValueReturns the value of thisTryif it is aSuccess, ornullif it is aFailure.default ValueReturns the successful value if this instance is aSuccess, or throws an exception if this instance is aFailure.default ValuegetOrThrow(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 booleanDetermines if the current instance represents a failure state.default booleanDetermines if the current instance represents a successful state.default <NewValue> Try<NewValue> Transforms the value held by this instance using the provided mapping function.mapFailure(Function<? super Throwable, ? extends Throwable> mapper) Transforms the failure cause using the given function, leaving aSuccessunchanged.static <V> Try<V> of(Try.CheckedSupplier<? extends V> supplier) Creates aTryinstance by executing the givenCheckedSupplier.Executes a specified action if this instance represents a failure.Performs the given action if the current instance represents a successful outcome.Recovers from a failure by applying a recovery function to the underlying throwable.recoverWith(Function<? super Throwable, Try<Value>> recoverFn) Recovers from a failure by applying the given recovery function to the cause of the failure.run(Try.CheckedRunnable runnable) Executes the providedCheckedRunnableand returns aTryinstance representing the outcome of the execution.Transforms an iterable ofTry<V>into a singleTry<List<V>>.Transforms a stream ofTry<V>into a singleTry<List<V>>.stream()Returns a single-elementStreamcontaining the success value, or an empty stream on failure.static <V> Try<V> success(V value) Creates a successfulTryinstance containing the provided value.toOption()Converts the current instance to an Option.toResult()Converts the currentTryinstance into aResultrepresentation.Converts thisTryinto aResult<Value, E>using a custom error mapper.Maps each element of an iterable throughmapperand collects the results into aTry<List<B>>.Maps each element of a stream throughmapperand collects the results into aTry<List<B>>.
-
Method Details
-
success
Creates a successfulTryinstance containing the provided value.- Type Parameters:
V- the type of the value contained in theTryinstance- Parameters:
value- the value to be wrapped in a successfulTryinstance- Returns:
- a
Tryinstance representing a successful computation containing the given value
-
failure
Creates aTryinstance 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
Tryinstance representing the failure
-
of
Creates aTryinstance by executing the givenCheckedSupplier. If the supplier executes successfully, aTrycontaining the result is returned. If an exception is thrown during execution, aTrycontaining the throwable is returned.- Type Parameters:
V- the type of the result supplied by theCheckedSupplier- Parameters:
supplier- theCheckedSupplierto execute- Returns:
- a
Tryinstance representing either a success with the supplied value or a failure with the thrown exception
-
run
Executes the providedCheckedRunnableand returns aTryinstance representing the outcome of the execution.Note on null value: On success the returned
Try<Void>wrapsnullas its value (sinceVoidhas no instances). This means that converting the result viatoOption()will always returnOption.none()— useisSuccess()orfold()instead to observe the outcome of arun()call.- Parameters:
runnable- theCheckedRunnableto be executed- Returns:
- a
Try<Void>representing the success or failure of the execution. On success, its value isnull; 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:
trueif the current instance is of typeFailure, otherwisefalse.
-
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
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
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
Trycontaining the mapped value if successful, or the original failure if unsuccessful
-
flatMap
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
-
onFailure
-
recover
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
Tryinstance 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
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 newTryinstance 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
Returns the value if this instance is aSuccess, or the specified fallback value if it is aFailure.- Parameters:
fallback- the value to return if this instance is aFailure.- Returns:
- the value of this instance if it is a
Success, or the specified fallback value if it is aFailure.
-
getOrElseGet
Returns the value of thisTryif it is aSuccess, or retrieves a fallback value using the providedfallbackSupplierif it is aFailure.- Parameters:
fallbackSupplier- aSupplierthat provides an alternative value to return if thisTryis aFailure.- Returns:
- the value of this
Tryif it is aSuccess, or the value supplied byfallbackSupplierif it is aFailure.
-
getOrNull
Returns the value of thisTryif it is aSuccess, ornullif it is aFailure.- Returns:
- the successful value if this
Tryis aSuccess, ornullif it is aFailure.
-
getOrThrow
Returns the successful value if this instance is aSuccess, or throws an exception if this instance is aFailure.- Returns:
- the successful value of this
Tryif it is aSuccess. - Throws:
Exception- if thisTryis aFailureand the failure cause is anException.RuntimeException- if thisTryis aFailureand the failure cause is not anException.
-
getOrThrow
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 currentTryinstance into a single value by applying one of two provided functions. If thisTryis aSuccess, theonSuccessfunction is applied to the value. If thisTryis aFailure, theonFailurefunction 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 thisTryis aSuccessonFailure- a function to apply to the cause if thisTryis aFailure- Returns:
- the result of applying the appropriate function based on the state of this
Try
-
filter
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 anIllegalArgumentException. If this is already a Failure, the result remains unchanged.On the Success path, if
predicateisnullor throws, aFailure(NullPointerException)orFailure(exception)is returned rather than propagating the error. An existingFailureis returned unchanged without evaluating the predicate, consistent with the Try philosophy of capturing throwables as values. See alsofilter(Predicate, Supplier)andfilter(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
predicateorthrowableSupplierisnull, or if either throws, aFailurewrapping the throwable is returned rather than propagating the error.throwableSupplieris only invoked when the predicate evaluates tofalse. An existingFailureis returned unchanged without evaluating the predicate or the supplier, consistent with the Try philosophy of capturing throwables as values. See alsofilter(Predicate)andfilter(Predicate, java.util.function.Function).- Parameters:
predicate- the condition to evaluate for the value if this is a SuccessthrowableSupplier- 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 thisTryusing a predicate and a contextual error function that receives the value that failed the test. If this is aFailure, it is returned unchanged. If this is aSuccessand the predicate returnsfalse, aFailureis returned with the throwable produced byerrorFnapplied 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
predicatethrows, the exception is captured and returned as aFailure; iferrorFnreturnsnull, aFailure(NullPointerException)is returned rather than propagating the NPE.errorFnis only invoked when the predicate evaluates tofalse. Note that anullpredicateorerrorFnis detected eagerly and does throwNullPointerExceptionbefore any value is tested, regardless of whether this instance is aSuccessorFailure. See alsofilter(Predicate)andfilter(Predicate, Supplier).- Parameters:
predicate- the condition to test the value; must not benullerrorFn- a function that produces the throwable when the predicate fails; must not benull; if it returnsnull, aFailure(NullPointerException)is returned- Returns:
- this instance if the predicate holds or this is already a
Failure; otherwise a newFailureproduced byerrorFn - Throws:
NullPointerException- ifpredicateorerrorFnisnull
-
toResult
Converts the currentTryinstance into aResultrepresentation. If thisTryis aSuccess, the resultingResultwill be "ok" with the successful value. If thisTryis aFailure, the resultingResultwill be "err" with the failure cause.- Returns:
- a
Resultinstance where the success value is mapped to "ok" and the failure cause is mapped to "err".
-
toResult
Converts thisTryinto aResult<Value, E>using a custom error mapper. If this is aSuccess, returnsOkwith the same value. If this is aFailure, applieserrorMapperto the cause and returnsErr.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 resultingResult- Parameters:
errorMapper- a function that maps the failure cause to the error value; must not returnnull- Returns:
Ok(value)on success, orErr(errorMapper.apply(cause))on failure- Throws:
NullPointerException- iferrorMapperisnullor returnsnull
-
fromResult
Converts aResultinto aTryinstance. If theResultis successful (contains a value), a successfulTryis returned. If theResultcontains an error, a failedTryis returned with the corresponding cause.- Type Parameters:
V- the type of the successful value- Parameters:
result- theResultto convert into aTry- Returns:
- a
Tryrepresenting either the successful value or the failure cause contained in theResult
-
mapFailure
Transforms the failure cause using the given function, leaving aSuccessunchanged. If this is aFailureandmapperitself throws, the thrown exception becomes the new cause (mirroring the behaviour ofmap(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 newThrowable; must not returnnull- Returns:
- this instance if
Success, or a newFailurewith the mapped cause; ifmapperreturnsnullor throws, the exception is wrapped as a newFailure - Throws:
NullPointerException- ifmapperitself isnull
-
stream
Returns a single-elementStreamcontaining the success value, or an empty stream on failure. MirrorsOption.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
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 anOptionto aTry. If theOptioncontains a value, a successfulTryis returned with that value. Otherwise, a failedTryis created using the supplied exception.- Type Parameters:
V- the type of the value contained in theOption.- Parameters:
opt- theOptionto be converted into aTry, must not be null.exceptionSupplier- the supplier of the exception to be used when theOptionis empty, must not be null.- Returns:
- a
Tryrepresenting either a success containing the value of theOption, or a failure containing the exception provided by the supplier.
-
sequence
Transforms an iterable ofTry<V>into a singleTry<List<V>>. If any element is aFailure, that failure is returned immediately (fail-fast). If all elements areSuccess, returnsSuccesscontaining an unmodifiable list of values in encounter order.- Type Parameters:
V- the value type- Parameters:
tries- the iterable of Try values; must not benulland must not containnullelements- Returns:
Success(List<V>)if all elements succeed, or the firstFailureencountered- Throws:
NullPointerException- iftriesisnullor contains anullelement
-
sequence
Transforms a stream ofTry<V>into a singleTry<List<V>>. If any element is aFailure, that failure is returned immediately (fail-fast) and the stream is closed. If all elements areSuccess, returnsSuccesscontaining an unmodifiable list of values in encounter order.- Type Parameters:
V- the value type- Parameters:
tries- the stream of Try values; must not benulland must not containnullelements- Returns:
Success(List<V>)if all elements succeed, or the firstFailureencountered- Throws:
NullPointerException- iftriesisnullor contains anullelement
-
traverse
Maps each element of an iterable throughmapperand collects the results into aTry<List<B>>. Fails fast on the firstFailurereturned by the mapper.- Type Parameters:
A- the input element typeB- the mapped value type- Parameters:
values- the iterable of input values; must not benullmapper- a function that maps each value to aTry; must not benulland must not returnnull- Returns:
Success(List<B>)if all mappings succeed, or the firstFailureproduced by the mapper- Throws:
NullPointerException- ifvaluesormapperisnull, or if the mapper returnsnull
-
traverse
Maps each element of a stream throughmapperand collects the results into aTry<List<B>>. Fails fast on the firstFailurereturned by the mapper; the stream is closed in all cases.- Type Parameters:
A- the input element typeB- the mapped value type- Parameters:
values- the stream of input values; must not benullmapper- a function that maps each value to aTry; must not benulland must not returnnull- Returns:
Success(List<B>)if all mappings succeed, or the firstFailureproduced by the mapper- Throws:
NullPointerException- ifvaluesormapperisnull, or if the mapper returnsnull
-