Interface Try<T>
-
- Type Parameters:
T- the type of the value in case of success
- All Superinterfaces:
java.lang.Iterable<T>,java.io.Serializable,Value<T>
- All Known Implementing Classes:
Try.Failure,Try.Success
public interface Try<T> extends Value<T>, java.io.Serializable
A control structure that allows writing safe code without explicitly managing try-catch blocks for exceptions.The following exceptions are considered fatal or non-recoverable:
- InterruptedException
- LinkageError
- ThreadDeath
- VirtualMachineError, including OutOfMemoryError and StackOverflowError
Note: Methods such as
get()may re-throw exceptions without declaring them. When used within aInvocationHandlerof a dynamic proxy, such exceptions will be wrapped inUndeclaredThrowableException. See Dynamic Proxy Classes for more details.
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static classTry.Failure<T>Represents a failedTrycontaining aThrowableas the cause.static classTry.Success<T>Represents a successfulTrycontaining a value.static classTry.WithResources1<T1 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on oneAutoCloseableresource.static classTry.WithResources2<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on twoAutoCloseableresources.static classTry.WithResources3<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on threeAutoCloseableresources.static classTry.WithResources4<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on fourAutoCloseableresources.static classTry.WithResources5<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on fiveAutoCloseableresources.static classTry.WithResources6<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on sixAutoCloseableresources.static classTry.WithResources7<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on sevenAutoCloseableresources.static classTry.WithResources8<T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable,T8 extends java.lang.AutoCloseable>ATry-with-resources builder that operates on eightAutoCloseableresources.
-
Field Summary
Fields Modifier and Type Field Description static longserialVersionUIDThe serial version UID for serialization.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default Try<T>andFinally(@NonNull java.lang.Runnable runnable)default Try<T>andFinallyTry(@NonNull CheckedRunnable runnable)Executes a givenCheckedRunnableafter thisTry, regardless of whether it is aTry.SuccessorTry.Failure.default Try<T>andThen(@NonNull java.lang.Runnable runnable)default Try<T>andThen(@NonNull java.util.function.Consumer<? super T> consumer)default Try<T>andThenTry(@NonNull CheckedConsumer<? super T> consumer)default Try<T>andThenTry(@NonNull CheckedRunnable runnable)default <R> Try<R>collect(@NonNull PartialFunction<? super T,? extends R> partialFunction)Transforms the value of thisTryusing the givenPartialFunctionif it is defined at the value.booleanequals(java.lang.Object o)Clarifies that values have a proper equals() method implemented.default Try<java.lang.Throwable>failed()static <T> Try<T>failure(java.lang.Throwable exception)Creates aTry.Failurecontaining the givenexception.default Try<T>filter(@NonNull java.util.function.Predicate<? super T> predicate)default Try<T>filter(@NonNull java.util.function.Predicate<? super T> predicate, java.util.function.Function<? super T,? extends java.lang.Throwable> errorProvider)Returns aTryif the givenPredicateevaluates totrue, otherwise returns aTry.Failurecreated by applying the given function to the value.default Try<T>filter(@NonNull java.util.function.Predicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> throwableSupplier)Returns aTryif the givenPredicateevaluates totrue, otherwise returns aTry.Failurecreated by the givenSupplierofThrowable.default Try<T>filterTry(@NonNull CheckedPredicate<? super T> predicate)Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.default Try<T>filterTry(@NonNull CheckedPredicate<? super T> predicate, CheckedFunction1<? super T,? extends java.lang.Throwable> errorProvider)Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.default Try<T>filterTry(@NonNull CheckedPredicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> throwableSupplier)Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.default <U> Try<U>flatMap(@NonNull java.util.function.Function<? super T,? extends Try<? extends U>> mapper)Transforms the value of thisTryusing the givenFunctionif it is aTry.Success, or returns thisTry.Failure.default <U> Try<U>flatMapTry(@NonNull CheckedFunction1<? super T,? extends Try<? extends U>> mapper)Transforms the value of thisTryusing the givenCheckedFunction1if it is aTry.Success, or returns thisTry.Failure.default <X> Xfold(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends X> ifFail, @NonNull java.util.function.Function<? super T,? extends X> f)Folds thisTryinto a single value by applying one of two functions: one for the failure case and one for the success case.Tget()Returns the value of thisTryif it is aTry.Success, or throws the underlying exception if it is aTry.Failure.java.lang.ThrowablegetCause()Returns the cause of failure if thisTryis aTry.Failure.default TgetOrElseGet(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> other)Returns the value of thisSuccess, or applies the given function to the cause if this is aTry.Failure.default <X extends java.lang.Throwable>
TgetOrElseThrow(@NonNull java.util.function.Function<? super java.lang.Throwable,X> exceptionProvider)Returns the value of thisTry.Success, or throws a provided exception if this is aTry.Failure.inthashCode()Clarifies that values have a proper hashCode() method implemented.default booleanisAsync()Indicates whether thisTryis computed asynchronously.booleanisEmpty()Checks whether thisTrycontains no value, i.e., it is aTry.Failure.booleanisFailure()Checks whether thisTryis aTry.Failure.default booleanisLazy()Indicates whether thisTryis evaluated lazily.default booleanisSingleValued()Indicates whether thisTryrepresents a single value.booleanisSuccess()Checks whether thisTryis aTry.Success.default @NonNull Iterator<T>iterator()Returns a richio.vavr.collection.Iterator.default <U> Try<U>map(@NonNull java.util.function.Function<? super T,? extends U> mapper)Shortcut formapTry(mapper::apply), seemapTry(CheckedFunction1).default Try<T>mapFailure(@NonNull API.Match.Case<? extends java.lang.Throwable,? extends java.lang.Throwable> @NonNull ... cases)Transforms the cause of thisTry.Failureusing the given sequence of match cases.default <U> Try<U>mapTo(U value)Maps the underlying value to another fixed value.default Try<java.lang.Void>mapToVoid()Maps the underlying value to Voiddefault <U> Try<U>mapTry(@NonNull CheckedFunction1<? super T,? extends U> mapper)Applies the given checked function to the value of thisTry.Success, or returns thisTry.Failureunchanged.static <T> Try<T>narrow(Try<? extends T> t)Narrows aTry<? extends T>toTry<T>using a type-safe cast.static <T> Try<T>of(@NonNull CheckedFunction0<? extends T> supplier)Creates aTryinstance from aCheckedFunction0.static <T> Try<T>ofCallable(@NonNull java.util.concurrent.Callable<? extends T> callable)Creates aTryinstance from aCallable.static <T> Try<T>ofSupplier(@NonNull java.util.function.Supplier<? extends T> supplier)Creates aTryinstance from aSupplier.default <X extends java.lang.Throwable>
Try<T>onFailure(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Consumer<? super X> action)Performs the given action if thisTryis aTry.Failureand the cause is an instance of the specified type.default Try<T>onFailure(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)Performs the given action if thisTryis aTry.Failure.default Try<T>onSuccess(@NonNull java.util.function.Consumer<? super T> action)Performs the given action if thisTryis aTry.Success.default Try<T>orElse(@NonNull Try<? extends T> other)default Try<T>orElse(@NonNull java.util.function.Supplier<? extends Try<? extends T>> supplier)Returns thisTryif it is aTry.Success, or aTrysupplied by the givenSupplierif this is aTry.Failure.default voidorElseRun(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)Executes the given action if thisTryis aTry.Failure.default Try<T>peek(@NonNull java.util.function.Consumer<? super T> action)Performs the given action if thisTryis aTry.Success, otherwise does nothing.default <X extends java.lang.Throwable>
Try<T>recover(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Function<? super X,? extends T> f)Attempts to recover from a failure if the cause is an instance of the specified exception type.default <X extends java.lang.Throwable>
Try<T>recover(@NonNull java.lang.Class<X> exceptionType, T value)Recovers thisTrywith the givenvalueif this is aTry.Failureand the underlying cause matches the specifiedexceptionType.default Try<T>recover(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> f)Recovers thisTryif it is aTry.Failureby applying the given recovery functionfto the underlying exception.default Try<T>recoverAllAndTry(@NonNull CheckedFunction0<? extends T> recoveryAttempt)default <X extends java.lang.Throwable>
Try<T>recoverAndTry(@NonNull java.lang.Class<X> exceptionType, @NonNull CheckedFunction0<? extends T> recoveryAttempt)Returnsthisif it is aTry.Success, or attempts to recover from a failure when the underlying cause is assignable to the specifiedexceptionTypeby evaluating the givenrecoveryAttempt(viaof(CheckedFunction0)).default <X extends java.lang.Throwable>
Try<T>recoverWith(@NonNull java.lang.Class<X> exceptionType, @NonNull Try<? extends T> recovered)Recovers thisTrywith the givenrecoveredvalue if this is aTry.Failureand the underlying cause is assignable to the specifiedexceptionType.default <X extends java.lang.Throwable>
Try<T>recoverWith(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Function<? super X,Try<? extends T>> f)Attempts to recover from a failure by applying the given recovery function if the cause matches the specified exception type.default Try<T>recoverWith(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends Try<? extends T>> f)Recovers thisTryif it is aTry.Failureby applying the given recovery functionfto the underlying exception.static Try<java.lang.Void>run(@NonNull CheckedRunnable runnable)Creates aTryinstance from aCheckedRunnable.static Try<java.lang.Void>runRunnable(@NonNull java.lang.Runnable runnable)Creates aTryinstance from aRunnable.static <T> Try<Seq<T>>sequence(@NonNull java.lang.Iterable<? extends Try<? extends T>> values)static <T> Try<T>success(T value)Creates aTry.Successcontaining the givenvalue.default Either<java.lang.Throwable,T>toEither()Converts thisTryto anEither.default <L> Either<L,T>toEither(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends L> throwableMapper)Converts thisTryto anEither, mapping the failure cause to a left value using the providedFunction.java.lang.StringtoString()Clarifies that values have a proper toString() method implemented.default Validation<java.lang.Throwable,T>toValidation()Converts thisTryto aValidation.default <U> Validation<U,T>toValidation(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends U> throwableMapper)Converts thisTryto aValidation, mapping the failure cause to an invalid value using the providedFunction.default <U> Utransform(@NonNull java.util.function.Function<? super Try<T>,? extends U> f)Transforms thisTryinto a value of another type using the provided function.static <T,U>
Try<Seq<U>>traverse(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.Function<? super T,? extends Try<? extends U>> mapper)static <T1 extends java.lang.AutoCloseable>
Try.WithResources1<T1>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier)Creates aTry-with-resources builder that operates on oneAutoCloseableresource.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable>
Try.WithResources2<T1,T2>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier)Creates aTry-with-resources builder that operates on twoAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable>
Try.WithResources3<T1,T2,T3>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier)Creates aTry-with-resources builder that operates on threeAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable>
Try.WithResources4<T1,T2,T3,T4>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier)Creates aTry-with-resources builder that operates on fourAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable>
Try.WithResources5<T1,T2,T3,T4,T5>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier)Creates aTry-with-resources builder that operates on fiveAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable>
Try.WithResources6<T1,T2,T3,T4,T5,T6>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier)Creates aTry-with-resources builder that operates on sixAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable>
Try.WithResources7<T1,T2,T3,T4,T5,T6,T7>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier, @NonNull CheckedFunction0<? extends T7> t7Supplier)Creates aTry-with-resources builder that operates on sevenAutoCloseableresources.static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable,T8 extends java.lang.AutoCloseable>
Try.WithResources8<T1,T2,T3,T4,T5,T6,T7,T8>withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier, @NonNull CheckedFunction0<? extends T7> t7Supplier, @NonNull CheckedFunction0<? extends T8> t8Supplier)Creates aTry-with-resources builder that operates on eightAutoCloseableresources.-
Methods inherited from interface io.vavr.Value
collect, collect, contains, corresponds, eq, exists, forAll, forEach, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, out, out, spliterator, stderr, stdout, stringPrefix, toArray, toCharSeq, toCompletableFuture, toEither, toEither, toInvalid, toInvalid, toJavaArray, toJavaArray, toJavaArray, toJavaCollection, toJavaList, toJavaList, toJavaMap, toJavaMap, toJavaMap, toJavaOptional, toJavaParallelStream, toJavaSet, toJavaSet, toJavaStream, toLeft, toLeft, toLinkedMap, toLinkedMap, toLinkedSet, toList, toMap, toMap, toOption, toPriorityQueue, toPriorityQueue, toQueue, toRight, toRight, toSet, toSortedMap, toSortedMap, toSortedMap, toSortedMap, toSortedSet, toSortedSet, toStream, toTree, toTree, toTry, toTry, toValid, toValid, toValidation, toValidation, toVector
-
-
-
-
Field Detail
-
serialVersionUID
static final long serialVersionUID
The serial version UID for serialization.- See Also:
- Constant Field Values
-
-
Method Detail
-
of
static <T> Try<T> of(@NonNull CheckedFunction0<? extends T> supplier)
Creates aTryinstance from aCheckedFunction0.If the supplier executes without throwing an exception, a
Try.Successcontaining the result is returned. If an exception occurs during execution, aTry.Failurewrapping the thrown exception is returned.- Type Parameters:
T- the type of the value returned by the supplier- Parameters:
supplier- the checked supplier to execute- Returns:
- a
Try.Successwith the supplier's result, or aTry.Failureif an exception is thrown - Throws:
java.lang.NullPointerException- ifsupplierisnull
-
ofSupplier
static <T> Try<T> ofSupplier(@NonNull java.util.function.Supplier<? extends T> supplier)
Creates aTryinstance from aSupplier.If the supplier executes without throwing an exception, a
Try.Successcontaining the result is returned. If an exception occurs during execution, aTry.Failurewrapping the thrown exception is returned.- Type Parameters:
T- the type of the value returned by the supplier- Parameters:
supplier- the supplier to execute- Returns:
- a
Try.Successwith the supplier's result, or aTry.Failureif an exception is thrown - Throws:
java.lang.NullPointerException- ifsupplierisnull
-
ofCallable
static <T> Try<T> ofCallable(@NonNull java.util.concurrent.Callable<? extends T> callable)
Creates aTryinstance from aCallable.If the callable executes without throwing an exception, a
Try.Successcontaining the result is returned. If an exception occurs during execution, aTry.Failurewrapping the thrown exception is returned.- Type Parameters:
T- the type of the value returned by the callable- Parameters:
callable- the callable to execute- Returns:
- a
Try.Successwith the callable's result, or aTry.Failureif an exception is thrown - Throws:
java.lang.NullPointerException- ifcallableisnull
-
run
static Try<java.lang.Void> run(@NonNull CheckedRunnable runnable)
Creates aTryinstance from aCheckedRunnable.If the runnable executes without throwing an exception, a
Try.Successcontainingnull(representing the absence of a value) is returned. If an exception occurs during execution, aTry.Failurewrapping the thrown exception is returned.- Parameters:
runnable- the checked runnable to execute- Returns:
- a
Try.Successwithnullif the runnable completes successfully, or aTry.Failureif an exception is thrown - Throws:
java.lang.NullPointerException- ifrunnableisnull
-
runRunnable
static Try<java.lang.Void> runRunnable(@NonNull java.lang.Runnable runnable)
Creates aTryinstance from aRunnable.If the runnable executes without throwing an exception, a
Try.Successcontainingnull(representing the absence of a value) is returned. If an exception occurs during execution, aTry.Failurewrapping the thrown exception is returned.- Parameters:
runnable- the runnable to execute- Returns:
- a
Try.Successwithnullif the runnable completes successfully, or aTry.Failureif an exception is thrown - Throws:
java.lang.NullPointerException- ifrunnableisnull
-
sequence
static <T> Try<Seq<T>> sequence(@NonNull java.lang.Iterable<? extends Try<? extends T>> values)
Transforms anIterableofTryinstances into a singleTrycontaining aSeqof all successful results.If any element in the input iterable is a
Try.Failure, the resultingTrywill also be aTry.Failure, containing the first encountered failure's cause.- Type Parameters:
T- the type of values contained in theTrys- Parameters:
values- anIterableofTryinstances- Returns:
- a
Trycontaining aSeqof all successful results, or aTry.Failureif any input is a failure - Throws:
java.lang.NullPointerException- ifvaluesisnull
-
traverse
static <T,U> Try<Seq<U>> traverse(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.Function<? super T,? extends Try<? extends U>> mapper)
Transforms anIterableof values into a singleTrycontaining aSeqof mapped results.Each value in the input iterable is mapped using the provided
mapperfunction, which produces aTry. If all mappings succeed, aTry.Successcontaining aSeqof results is returned. If any mapping results in aTry.Failure, the first encountered failure is returned.- Type Parameters:
T- the type of the input valuesU- the type of the mapped results- Parameters:
values- anIterableof input valuesmapper- a function mapping each input value to aTryof the mapped result- Returns:
- a
Trycontaining aSeqof all mapped results, or aTry.Failureif any mapping fails - Throws:
java.lang.NullPointerException- ifvaluesormapperisnull
-
success
static <T> Try<T> success(T value)
Creates aTry.Successcontaining the givenvalue.This is a convenience method equivalent to
new Success<>(value).- Type Parameters:
T- the type of the value- Parameters:
value- the value to wrap in aTry.Success- Returns:
- a new
Try.Successcontainingvalue
-
failure
static <T> Try<T> failure(java.lang.Throwable exception)
Creates aTry.Failurecontaining the givenexception.This is a convenience method equivalent to
new Failure<>(exception).- Type Parameters:
T- the component type of theTry- Parameters:
exception- the exception to wrap in aTry.Failure- Returns:
- a new
Try.Failurecontainingexception
-
narrow
static <T> Try<T> narrow(Try<? extends T> t)
Narrows aTry<? extends T>toTry<T>using a type-safe cast.This is safe because
Tryis immutable and its contents are read-only, allowing covariance.- Type Parameters:
T- the component type of theTry- Parameters:
t- theTryinstance to narrow- Returns:
- the given
Tryinstance asTry<T>
-
andThen
default Try<T> andThen(@NonNull java.util.function.Consumer<? super T> consumer)
Performs the givenConsumeron the value of thisTryif it is aTry.Success.This is a shortcut for
andThenTry(consumer::accept). If thisTryis aTry.Failure, it is returned unchanged. If the consumer throws an exception, aTry.Failureis returned.- Parameters:
consumer- the consumer to execute on the value- Returns:
- this
Tryif it is aTry.Failureor the consumer succeeds, otherwise aTry.Failureof the consumer - Throws:
java.lang.NullPointerException- ifconsumerisnull- See Also:
andThenTry(CheckedConsumer)
-
andThenTry
default Try<T> andThenTry(@NonNull CheckedConsumer<? super T> consumer)
Passes the result of thisTryto the givenCheckedConsumerif this is aTry.Success.This allows chaining of operations that may throw checked exceptions. If this
Tryis aTry.Failure, it is returned unchanged. If the consumer throws an exception, aTry.Failurecontaining that exception is returned.Example usage:
Try.of(() -> 100) .andThenTry(i -> System.out.println(i));- Parameters:
consumer- the checked consumer to execute on the value- Returns:
- this
Tryif it is aTry.Failureor the consumer succeeds, otherwise aTry.Failureof the consumer - Throws:
java.lang.NullPointerException- ifconsumerisnull
-
andThen
default Try<T> andThen(@NonNull java.lang.Runnable runnable)
Performs the givenRunnableif thisTryis aTry.Success.This is a shortcut for
andThenTry(runnable::run). If thisTryis aTry.Failure, it is returned unchanged. If the runnable throws an exception, aTry.Failurecontaining that exception is returned.- Parameters:
runnable- the runnable to execute- Returns:
- this
Tryif it is aTry.Failureor the runnable succeeds, otherwise aTry.Failureof the runnable - Throws:
java.lang.NullPointerException- ifrunnableisnull- See Also:
andThenTry(CheckedRunnable)
-
andThenTry
default Try<T> andThenTry(@NonNull CheckedRunnable runnable)
Executes the givenCheckedRunnableif thisTryis aTry.Success; otherwise, returns thisFailure.This allows chaining of runnables that may throw checked exceptions. If the runnable throws an exception, a
Try.Failurecontaining that exception is returned.Example usage with method references:
The following two forms are semantically equivalent:Try.run(A::methodRef) .andThen(B::methodRef) .andThen(C::methodRef);Try.run(this::doStuff) .andThen(this::doMoreStuff) .andThen(this::doEvenMoreStuff); Try.run(() -> { doStuff(); doMoreStuff(); doEvenMoreStuff(); });- Parameters:
runnable- the checked runnable to execute- Returns:
- this
Tryif it is aTry.Failureor the runnable succeeds, otherwise aTry.Failureof the runnable - Throws:
java.lang.NullPointerException- ifrunnableisnull
-
collect
default <R> Try<R> collect(@NonNull PartialFunction<? super T,? extends R> partialFunction)
Transforms the value of thisTryusing the givenPartialFunctionif it is defined at the value.The
partialFunctionis first tested withPartialFunction.isDefinedAt(Object). If it returnstrue, the value is mapped usingPartialFunction.apply(Object)and wrapped in a newTry. If the function is not defined at the value or thisTryis aTry.Failure, the result is aTry.Failure.Example:
PartialFunction<Integer, String> pf = ...; Try.of(() -> 42) .collect(pf); // maps the value if pf.isDefinedAt(42) is true- Type Parameters:
R- the type of the mapped result- Parameters:
partialFunction- a function that may not be defined for all input values- Returns:
- a new
Trycontaining the mapped value if defined, or aTry.Failure - Throws:
java.lang.NullPointerException- ifpartialFunctionisnull
-
failed
default Try<java.lang.Throwable> failed()
Returns aSuccesscontaining the throwable if thisTryis aTry.Failure.If this
Tryis aTry.Success, aFailurecontaining aNoSuchElementExceptionis returned.- Returns:
- a
Try<Throwable>representing the throwable of thisTry.Failure, or aTry.Failureif this is aTry.Success
-
filter
default Try<T> filter(@NonNull java.util.function.Predicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> throwableSupplier)
Returns aTryif the givenPredicateevaluates totrue, otherwise returns aTry.Failurecreated by the givenSupplierofThrowable.This is a shortcut for
filterTry(CheckedPredicate, Supplier).- Parameters:
predicate- the predicate to test the valuethrowableSupplier- a supplier providing a throwable if the predicate fails- Returns:
- this
Tryif the predicate passes, otherwise aTry.Failurefrom the throwable supplier - Throws:
java.lang.NullPointerException- ifpredicateorthrowableSupplierisnull
-
filter
default Try<T> filter(@NonNull java.util.function.Predicate<? super T> predicate, java.util.function.Function<? super T,? extends java.lang.Throwable> errorProvider)
Returns aTryif the givenPredicateevaluates totrue, otherwise returns aTry.Failurecreated by applying the given function to the value.This is a shortcut for
filterTry(CheckedPredicate, CheckedFunction1).- Parameters:
predicate- the predicate to test the valueerrorProvider- a function providing a throwable if the predicate fails- Returns:
- this
Tryif the predicate passes, otherwise aTry.Failurefrom the error provider - Throws:
java.lang.NullPointerException- ifpredicateorerrorProviderisnull
-
filter
default Try<T> filter(@NonNull java.util.function.Predicate<? super T> predicate)
Returns aTryif the givenPredicateevaluates totrue, otherwise returns aTry.Failure.This is a shortcut for
filterTry(CheckedPredicate).- Parameters:
predicate- the predicate to test the value- Returns:
- this
Tryif the predicate passes, otherwise aTry.Failure - Throws:
java.lang.NullPointerException- ifpredicateisnull
-
filterTry
default Try<T> filterTry(@NonNull CheckedPredicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> throwableSupplier)
Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.If this is a
Try.Successand the predicate returnsfalse, or if evaluating the predicate throws an exception, a newTry.Failureis returned. The returned failure wraps aThrowableprovided by the giventhrowableSupplier.- Parameters:
predicate- the checked predicate to test the valuethrowableSupplier- a supplier providing theThrowablefor the failure if the predicate does not hold- Returns:
- this
Tryif it is aTry.Failureor the predicate passes, otherwise aTry.Failurefrom the supplier - Throws:
java.lang.NullPointerException- ifpredicateorthrowableSupplierisnull
-
filterTry
default Try<T> filterTry(@NonNull CheckedPredicate<? super T> predicate, CheckedFunction1<? super T,? extends java.lang.Throwable> errorProvider)
Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.If the predicate does not hold or throws an exception, a new
Try.Failureis returned. The returned failure wraps aThrowableprovided by the givenerrorProviderfunction.- Parameters:
predicate- the checked predicate to test the valueerrorProvider- a function that provides aThrowableif the predicate fails- Returns:
- this
Tryif it is aTry.Failureor the predicate passes, otherwise aTry.Failurefrom the error provider - Throws:
java.lang.NullPointerException- ifpredicateorerrorProviderisnull
-
filterTry
default Try<T> filterTry(@NonNull CheckedPredicate<? super T> predicate)
Returnsthisif thisTryis aTry.Failureor if it is aTry.Successand the value satisfies the given checked predicate.If the predicate does not hold or throws an exception, a new
Try.Failurewrapping aNoSuchElementExceptionis returned.- Parameters:
predicate- the checked predicate to test the value- Returns:
- this
Tryif it is aTry.Failureor the predicate passes, otherwise aTry.Failurewith aNoSuchElementException - Throws:
java.lang.NullPointerException- ifpredicateisnull
-
flatMap
default <U> Try<U> flatMap(@NonNull java.util.function.Function<? super T,? extends Try<? extends U>> mapper)
Transforms the value of thisTryusing the givenFunctionif it is aTry.Success, or returns thisTry.Failure.This is a shortcut for
flatMapTry(CheckedFunction1).- Type Parameters:
U- the type of the resultingTry- Parameters:
mapper- a function mapping the value to anotherTry- Returns:
- a new
Tryresulting from applying the mapper, or thisFailureif this is a failure - Throws:
java.lang.NullPointerException- ifmapperisnull
-
flatMapTry
default <U> Try<U> flatMapTry(@NonNull CheckedFunction1<? super T,? extends Try<? extends U>> mapper)
Transforms the value of thisTryusing the givenCheckedFunction1if it is aTry.Success, or returns thisTry.Failure.If applying the mapper throws an exception, a
Try.Failurecontaining the exception is returned.- Type Parameters:
U- the type of the resultingTry- Parameters:
mapper- a checked function mapping the value to anotherTry- Returns:
- a new
Tryresulting from applying the mapper, or thisFailureif this is a failure - Throws:
java.lang.NullPointerException- ifmapperisnull
-
get
T get()
Returns the value of thisTryif it is aTry.Success, or throws the underlying exception if it is aTry.Failure.Important: If this
Tryis aTry.Failure, the exception thrown is exactly thegetCause()of thisFailure. The underlying cause is thrown sneakily (without being declared in the method signature).
-
getCause
java.lang.Throwable getCause()
Returns the cause of failure if thisTryis aTry.Failure.- Returns:
- the throwable cause of this
Try.Failure - Throws:
java.lang.UnsupportedOperationException- if thisTryis aTry.Success
-
isAsync
default boolean isAsync()
Indicates whether thisTryis computed asynchronously.
-
isEmpty
boolean isEmpty()
Checks whether thisTrycontains no value, i.e., it is aTry.Failure.- Specified by:
isEmptyin interfaceValue<T>- Returns:
trueif this is aTry.Failure,falseif this is aTry.Success
-
isFailure
boolean isFailure()
Checks whether thisTryis aTry.Failure.- Returns:
trueif this is aTry.Failure,falseif this is aTry.Success
-
isLazy
default boolean isLazy()
Indicates whether thisTryis evaluated lazily.
-
isSingleValued
default boolean isSingleValued()
Indicates whether thisTryrepresents a single value.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
true, since aTryalways contains at most one value
-
isSuccess
boolean isSuccess()
Checks whether thisTryis aTry.Success.- Returns:
trueif this is aTry.Success,falseif this is aTry.Failure
-
iterator
default @NonNull Iterator<T> iterator()
Description copied from interface:ValueReturns a richio.vavr.collection.Iterator.
-
map
default <U> Try<U> map(@NonNull java.util.function.Function<? super T,? extends U> mapper)
Shortcut formapTry(mapper::apply), seemapTry(CheckedFunction1).
-
mapTo
default <U> Try<U> mapTo(U value)
Description copied from interface:ValueMaps the underlying value to another fixed value.
-
mapToVoid
default Try<java.lang.Void> mapToVoid()
Description copied from interface:ValueMaps the underlying value to Void
-
mapFailure
@GwtIncompatible default Try<T> mapFailure(@NonNull API.Match.Case<? extends java.lang.Throwable,? extends java.lang.Throwable> @NonNull ... cases)
Transforms the cause of thisTry.Failureusing the given sequence of match cases.If this
Tryis aTry.Success, it is returned unchanged. If this is aTry.Failure, the cause is matched against the providedcases. If a match is found, a newTry.Failurecontaining the mapped exception is returned. If none of the cases match, the originalTry.Failureis returned.- Parameters:
cases- a possibly non-exhaustive sequence of match cases to handle the cause- Returns:
- a new
Trywith a mapped cause if a match is found, otherwise thisTry
-
mapTry
default <U> Try<U> mapTry(@NonNull CheckedFunction1<? super T,? extends U> mapper)
Applies the given checked function to the value of thisTry.Success, or returns thisTry.Failureunchanged.If the function throws an exception, a new
Try.Failurecontaining the exception is returned. This allows chaining of computations that may throw checked exceptions.Example:
Try.of(() -> 0) .mapTry(x -> 1 / x); // division by zero will result in a Failure- Type Parameters:
U- the type of the result- Parameters:
mapper- a checked function to apply to the value- Returns:
- a new
Trycontaining the mapped value if this is aTry.Success, otherwise thisTry.Failure - Throws:
java.lang.NullPointerException- ifmapperisnull
-
onFailure
default Try<T> onFailure(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)
Performs the given action if thisTryis aTry.Failure.Example:
// 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- a consumer of the throwable cause- Returns:
- this
Tryinstance - Throws:
java.lang.NullPointerException- ifactionis null
-
onFailure
@GwtIncompatible default <X extends java.lang.Throwable> Try<T> onFailure(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Consumer<? super X> action)
Performs the given action if thisTryis aTry.Failureand the cause is an instance of the specified type.Example:
// does not print anything Try.success(1).onFailure(Error.class, System.out::println); // prints "Error" Try.failure(new Error()) .onFailure(RuntimeException.class, x -> System.out.println("Runtime exception")) .onFailure(Error.class, x -> System.out.println("Error"));- Type Parameters:
X- the type of exception that should be handled- Parameters:
exceptionType- the type of exception to handleaction- a consumer for the exception- Returns:
- this
Tryinstance - Throws:
java.lang.NullPointerException- ifexceptionTypeoractionis null
-
onSuccess
default Try<T> onSuccess(@NonNull java.util.function.Consumer<? super T> action)
Performs the given action if thisTryis aTry.Success.Example:
// prints "1" Try.success(1).onSuccess(System.out::println); // does not print anything Try.failure(new Error()).onSuccess(System.out::println);- Parameters:
action- a consumer of the value- Returns:
- this
Tryinstance - Throws:
java.lang.NullPointerException- ifactionis null
-
orElse
default Try<T> orElse(@NonNull Try<? extends T> other)
- Parameters:
other- the alternativeTryto return if this is aTry.Failure- Returns:
- this
Tryif success, otherwiseother - Throws:
java.lang.NullPointerException- ifotheris null
-
orElse
default Try<T> orElse(@NonNull java.util.function.Supplier<? extends Try<? extends T>> supplier)
Returns thisTryif it is aTry.Success, or aTrysupplied by the givenSupplierif this is aTry.Failure.The supplier is only invoked if this
Tryis aTry.Failure.- Parameters:
supplier- a supplier of an alternativeTry- Returns:
- this
Tryif success, otherwise theTryreturned bysupplier - Throws:
java.lang.NullPointerException- ifsupplieris null
-
getOrElseGet
default T getOrElseGet(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> other)
Returns the value of thisSuccess, or applies the given function to the cause if this is aTry.Failure.- Parameters:
other- a function mapping the throwable cause to a replacement value- Returns:
- the value of this
Try.Success, or the result of applyingotherto the failure cause - Throws:
java.lang.NullPointerException- ifotheris null
-
orElseRun
default void orElseRun(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)
Executes the given action if thisTryis aTry.Failure.This method is typically used for side-effecting handling of failure cases.
- Parameters:
action- a consumer of the throwable cause- Throws:
java.lang.NullPointerException- ifactionis null
-
getOrElseThrow
default <X extends java.lang.Throwable> T getOrElseThrow(@NonNull java.util.function.Function<? super java.lang.Throwable,X> exceptionProvider) throws X extends java.lang.Throwable
Returns the value of thisTry.Success, or throws a provided exception if this is aTry.Failure.The exception to throw is created by applying the given
exceptionProviderfunction to the cause of the failure.- Type Parameters:
X- the type of the exception to throw- Parameters:
exceptionProvider- a function mapping the throwable cause to an exception to be thrown- Returns:
- the value of this
Try.Success - Throws:
X- the exception provided byexceptionProviderif this is aTry.Failurejava.lang.NullPointerException- ifexceptionProvideris nullX extends java.lang.Throwable
-
fold
default <X> X fold(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends X> ifFail, @NonNull java.util.function.Function<? super T,? extends X> f)Folds thisTryinto a single value by applying one of two functions: one for the failure case and one for the success case.If this is a
Try.Failure, theifFailfunction is applied to the cause. If this is aTry.Success, theffunction is applied to the value.- Type Parameters:
X- the type of the result- Parameters:
ifFail- maps the throwable cause if this is aTry.Failuref- maps the value if this is aTry.Success- Returns:
- the result of applying the corresponding function
-
peek
default Try<T> peek(@NonNull java.util.function.Consumer<? super T> action)
Performs the given action if thisTryis aTry.Success, otherwise does nothing.This method is useful for side-effecting operations without transforming the value.
-
recover
@GwtIncompatible default <X extends java.lang.Throwable> Try<T> recover(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Function<? super X,? extends T> f)
Attempts to recover from a failure if the cause is an instance of the specified exception type.If this
Tryis aTry.Success, it is returned unchanged. If this is aTry.Failureand the cause is assignable fromexceptionType, the recovery functionfis applied to the cause inside a newTry. Otherwise, the originalFailureis returned.Example:
// = 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- the type of exception to handle- Parameters:
exceptionType- the specific exception type that should be recoveredf- a recovery function taking an exception of typeXand producing a value- Returns:
- a
Successwith the recovered value if the exception matches, otherwise thisTry - Throws:
java.lang.NullPointerException- ifexceptionTypeorfis null
-
recoverWith
@GwtIncompatible default <X extends java.lang.Throwable> Try<T> recoverWith(@NonNull java.lang.Class<X> exceptionType, @NonNull java.util.function.Function<? super X,Try<? extends T>> f)
Attempts to recover from a failure by applying the given recovery function if the cause matches the specified exception type.If this
Tryis aTry.Success, it is returned unchanged. If this is aTry.Failureand the cause is assignable fromexceptionType, the recovery functionfis applied to the cause and returns a newTry. If the returnedTryis aisFailure(), the recovery is considered unsuccessful. Otherwise, the originalFailureis returned.Example:
// = 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- the type of exception to handle- Parameters:
exceptionType- the specific exception type that should trigger recoveryf- a recovery function that takes an exception of typeXand returns a newTryinstance- Returns:
- a
Tryrepresenting the recovered value if the exception matches, otherwise thisTry - Throws:
java.lang.NullPointerException- ifexceptionTypeorfis null
-
recoverWith
@GwtIncompatible default <X extends java.lang.Throwable> Try<T> recoverWith(@NonNull java.lang.Class<X> exceptionType, @NonNull Try<? extends T> recovered)
Recovers thisTrywith the givenrecoveredvalue if this is aTry.Failureand the underlying cause is assignable to the specifiedexceptionType.If this
Tryis aTry.Success, or if the cause does not matchexceptionType, the originalTryis returned unchanged.Example:
// = Success(13) Try.of(() -> 27/2).recoverWith(ArithmeticException.class, Try.success(Integer.MAX_VALUE)); // = Success(2147483647) Try.of(() -> 1/0) .recoverWith(Error.class, Try.success(-1)) .recoverWith(ArithmeticException.class, Try.success(Integer.MAX_VALUE)); // = Failure(java.lang.ArithmeticException: / by zero) Try.of(() -> 1/0).recoverWith(Error.class, Try.success(Integer.MAX_VALUE));- Type Parameters:
X- the type of exception to handle- Parameters:
exceptionType- the exception type that triggers recoveryrecovered- aTryinstance to return if the cause matchesexceptionType- Returns:
- the given
recoveredif the exception matches, otherwise thisTry - Throws:
java.lang.NullPointerException- ifexceptionTypeorrecoveredis null
-
recover
@GwtIncompatible default <X extends java.lang.Throwable> Try<T> recover(@NonNull java.lang.Class<X> exceptionType, T value)
Recovers thisTrywith the givenvalueif this is aTry.Failureand the underlying cause matches the specifiedexceptionType.If this
Tryis aTry.Success, or if the cause is not assignable fromexceptionType, the originalTryis returned unchanged.Example:
// = Success(13) Try.of(() -> 27/2).recover(ArithmeticException.class, 13); // = Success(2147483647) Try.of(() -> 1/0) .recover(Error.class, -1) .recover(ArithmeticException.class, Integer.MAX_VALUE); // = Failure(java.lang.ArithmeticException: / by zero) Try.of(() -> 1/0).recover(Error.class, Integer.MAX_VALUE);- Type Parameters:
X- the type of exception to handle- Parameters:
exceptionType- the exception type that triggers recoveryvalue- the value to return in aTry.Successif the cause matches- Returns:
- a
Trycontaining the recovery value if the exception matches, otherwise thisTry - Throws:
java.lang.NullPointerException- ifexceptionTypeis null
-
recover
default Try<T> recover(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> f)
Recovers thisTryif it is aTry.Failureby applying the given recovery functionfto the underlying exception. The result of the function is wrapped in aTry.Success.If this
Tryis already aTry.Success, it is returned unchanged.Example:
// = Success(13) Try.of(() -> 27/2).recover(x -> Integer.MAX_VALUE); // = Success(2147483647) Try.of(() -> 1/0).recover(x -> Integer.MAX_VALUE);- Parameters:
f- A recovery function that takes the underlying exception and returns a value- Returns:
- a
Trycontaining either the original success value or the recovered value - Throws:
java.lang.NullPointerException- iffis null
-
recoverWith
default Try<T> recoverWith(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends Try<? extends T>> f)
Recovers thisTryif it is aTry.Failureby applying the given recovery functionfto the underlying exception. The recovery function returns a newTryinstance.If this
Tryis already aTry.Success, it is returned unchanged. If an exception occurs while executing the recovery function, a newTry.Failureis returned wrapping that exception.Example:
// = Success(13) Try.of(() -> 27/2).recoverWith(x -> Try.success(Integer.MAX_VALUE)); // = Success(2147483647) Try.of(() -> 1/0).recoverWith(x -> Try.success(Integer.MAX_VALUE));- Parameters:
f- A recovery function that takes the underlying exception and returns a newTry- Returns:
- a
Trycontaining either the original success value or the recoveredTry - Throws:
java.lang.NullPointerException- iffis null
-
recoverAllAndTry
default Try<T> recoverAllAndTry(@NonNull CheckedFunction0<? extends T> recoveryAttempt)
Recovers from any failure by evaluating the givenrecoveryAttemptif thisTryis aTry.Failure.If this
Tryis already aTry.Success, it is returned unchanged. TherecoveryAttemptis evaluated usingof(CheckedFunction0), and its result is wrapped in a newTry.Example:
// = Success(5) Try.of(() -> 5) .recoverAllAndTry(() -> 10); // = Success(10) Try.of(() -> 1/0) .recoverAllAndTry(() -> 10);- Parameters:
recoveryAttempt- A checked supplier providing a fallback value in case of failure- Returns:
- a
Trycontaining either the original success value or the result ofrecoveryAttempt - Throws:
java.lang.NullPointerException- ifrecoveryAttemptis null
-
recoverAndTry
default <X extends java.lang.Throwable> Try<T> recoverAndTry(@NonNull java.lang.Class<X> exceptionType, @NonNull CheckedFunction0<? extends T> recoveryAttempt)
Returnsthisif it is aTry.Success, or attempts to recover from a failure when the underlying cause is assignable to the specifiedexceptionTypeby evaluating the givenrecoveryAttempt(viaof(CheckedFunction0)).Example usage:
// = Success(5) Try.of(() -> 5) .recoverAndTry(ArithmeticException.class, () -> 10); // = Success(10) Try.of(() -> 1/0) .recoverAndTry(ArithmeticException.class, () -> 10); // = Failure(java.lang.ArithmeticException: / by zero) Try.of(() -> 1/0) .recoverAndTry(NullPointerException.class, () -> 10);- Type Parameters:
X- The type of the exception that may be recovered- Parameters:
exceptionType- The specific exception type that triggers the recoveryrecoveryAttempt- A checked function providing a fallback value if the exception matches- Returns:
- a
Trycontaining either the original success value or the result ofrecoveryAttempt - Throws:
java.lang.NullPointerException- ifexceptionTypeorrecoveryAttemptis null
-
toEither
default Either<java.lang.Throwable,T> toEither()
Converts thisTryto anEither.If this is a
Try.Success, the value is wrapped as aEither.right(Object). If this is aTry.Failure, the cause is wrapped as aEither.left(Object).- Returns:
- a new
Eitherrepresenting thisTry
-
toEither
default <L> Either<L,T> toEither(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends L> throwableMapper)
Converts thisTryto anEither, mapping the failure cause to a left value using the providedFunction.- Type Parameters:
L- the left type of the resultingEither- Parameters:
throwableMapper- a function to convert the failureThrowableto typeL- Returns:
- a new
Eitherrepresenting thisTry - Throws:
java.lang.NullPointerException- ifthrowableMapperis null
-
toValidation
default Validation<java.lang.Throwable,T> toValidation()
Converts thisTryto aValidation.A
Try.Successis converted to aValidation.valid(Object), while aTry.Failureis converted to aValidation.invalid(Object)containing the cause.- Returns:
- a new
Validationrepresenting thisTry
-
toValidation
default <U> Validation<U,T> toValidation(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends U> throwableMapper)
Converts thisTryto aValidation, mapping the failure cause to an invalid value using the providedFunction.Validation<String, Integer> validation = Try.of(() -> 1/0).toValidation(Throwable::getMessage);- Type Parameters:
U- the type of the invalid value- Parameters:
throwableMapper- a function to convert the failureThrowableto typeU- Returns:
- a
Validationrepresenting thisTry - Throws:
java.lang.NullPointerException- ifthrowableMapperis null
-
transform
default <U> U transform(@NonNull java.util.function.Function<? super Try<T>,? extends U> f)
Transforms thisTryinto a value of another type using the provided function.- Type Parameters:
U- the result type of the transformation- Parameters:
f- a transformation function- Returns:
- the result of applying
fto thisTry - Throws:
java.lang.NullPointerException- iffis null
-
andFinally
default Try<T> andFinally(@NonNull java.lang.Runnable runnable)
- Parameters:
runnable- a final action to perform- Returns:
- this
Tryunchanged if the runnable succeeds, or a newTry.Failureif it throws - Throws:
java.lang.NullPointerException- ifrunnableis null
-
andFinallyTry
default Try<T> andFinallyTry(@NonNull CheckedRunnable runnable)
Executes a givenCheckedRunnableafter thisTry, regardless of whether it is aTry.SuccessorTry.Failure.- Parameters:
runnable- a checked final action to perform- Returns:
- this
Tryunchanged if the runnable succeeds, or a newTry.Failureif it throws - Throws:
java.lang.NullPointerException- ifrunnableis null
-
equals
boolean equals(java.lang.Object o)
Description copied from interface:ValueClarifies that values have a proper equals() method implemented.
-
hashCode
int hashCode()
Description copied from interface:ValueClarifies that values have a proper hashCode() method implemented.See Object.hashCode().
-
toString
java.lang.String toString()
Description copied from interface:ValueClarifies that values have a proper toString() method implemented.See Object.toString().
-
withResources
static <T1 extends java.lang.AutoCloseable> Try.WithResources1<T1> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier)
Creates aTry-with-resources builder that operates on oneAutoCloseableresource.- Type Parameters:
T1- Type of the 1st resource.- Parameters:
t1Supplier- The supplier of the first resource.- Returns:
- a new
Try.WithResources1instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable> Try.WithResources2<T1,T2> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier)
Creates aTry-with-resources builder that operates on twoAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.- Returns:
- a new
Try.WithResources2instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable> Try.WithResources3<T1,T2,T3> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier)
Creates aTry-with-resources builder that operates on threeAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.- Returns:
- a new
Try.WithResources3instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable> Try.WithResources4<T1,T2,T3,T4> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier)
Creates aTry-with-resources builder that operates on fourAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.T4- Type of the 4th resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.t4Supplier- The supplier of the 4th resource.- Returns:
- a new
Try.WithResources4instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable> Try.WithResources5<T1,T2,T3,T4,T5> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier)
Creates aTry-with-resources builder that operates on fiveAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.T4- Type of the 4th resource.T5- Type of the 5th resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.t4Supplier- The supplier of the 4th resource.t5Supplier- The supplier of the 5th resource.- Returns:
- a new
Try.WithResources5instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable> Try.WithResources6<T1,T2,T3,T4,T5,T6> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier)
Creates aTry-with-resources builder that operates on sixAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.T4- Type of the 4th resource.T5- Type of the 5th resource.T6- Type of the 6th resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.t4Supplier- The supplier of the 4th resource.t5Supplier- The supplier of the 5th resource.t6Supplier- The supplier of the 6th resource.- Returns:
- a new
Try.WithResources6instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable> Try.WithResources7<T1,T2,T3,T4,T5,T6,T7> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier, @NonNull CheckedFunction0<? extends T7> t7Supplier)
Creates aTry-with-resources builder that operates on sevenAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.T4- Type of the 4th resource.T5- Type of the 5th resource.T6- Type of the 6th resource.T7- Type of the 7th resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.t4Supplier- The supplier of the 4th resource.t5Supplier- The supplier of the 5th resource.t6Supplier- The supplier of the 6th resource.t7Supplier- The supplier of the 7th resource.- Returns:
- a new
Try.WithResources7instance.
-
withResources
static <T1 extends java.lang.AutoCloseable,T2 extends java.lang.AutoCloseable,T3 extends java.lang.AutoCloseable,T4 extends java.lang.AutoCloseable,T5 extends java.lang.AutoCloseable,T6 extends java.lang.AutoCloseable,T7 extends java.lang.AutoCloseable,T8 extends java.lang.AutoCloseable> Try.WithResources8<T1,T2,T3,T4,T5,T6,T7,T8> withResources(@NonNull CheckedFunction0<? extends T1> t1Supplier, @NonNull CheckedFunction0<? extends T2> t2Supplier, @NonNull CheckedFunction0<? extends T3> t3Supplier, @NonNull CheckedFunction0<? extends T4> t4Supplier, @NonNull CheckedFunction0<? extends T5> t5Supplier, @NonNull CheckedFunction0<? extends T6> t6Supplier, @NonNull CheckedFunction0<? extends T7> t7Supplier, @NonNull CheckedFunction0<? extends T8> t8Supplier)
Creates aTry-with-resources builder that operates on eightAutoCloseableresources.- Type Parameters:
T1- Type of the 1st resource.T2- Type of the 2nd resource.T3- Type of the 3rd resource.T4- Type of the 4th resource.T5- Type of the 5th resource.T6- Type of the 6th resource.T7- Type of the 7th resource.T8- Type of the 8th resource.- Parameters:
t1Supplier- The supplier of the 1st resource.t2Supplier- The supplier of the 2nd resource.t3Supplier- The supplier of the 3rd resource.t4Supplier- The supplier of the 4th resource.t5Supplier- The supplier of the 5th resource.t6Supplier- The supplier of the 6th resource.t7Supplier- The supplier of the 7th resource.t8Supplier- The supplier of the 8th resource.- Returns:
- a new
Try.WithResources8instance.
-
-