Class Try<T>
- java.lang.Object
-
- io.vavr.control.Try<T>
-
- Type Parameters:
T
- Value type of a successful computation
- All Implemented Interfaces:
Iterable<T>
,java.io.Serializable
,java.lang.Iterable<T>
public abstract class Try<T> extends java.lang.Object implements Iterable<T>, java.io.Serializable
TheTry
control gives us the ability to write safe code without focusing on try-catch blocks in the presence of exceptions.A real-world use-case is to defer error handling and recovery to outer applications layers. With
Try
, we achieve this by capturing the error state of a computation and passing it around.Try
has one of two states,Success
andFailure
. ASuccess
wraps the value of a given computation, aFailure
wraps an exception that occurred during the computation.The following exceptions are considered to be fatal/non-recoverable and will be re-thrown:
- LinkageError
- ThreadDeath
- VirtualMachineError (i.e. OutOfMemoryError or StackOverflowError)
Creation
Try is intended to be used as value which contains the result of a computation. For that purpose,of(Callable)
is called. See alsosuccess(Object)
andfailure(Throwable)
.However, some use
Try
as syntactic sugar for try-catch blocks that only perform side-effects. For that purpose,run(CheckedRunnable)
is called. This variant does not contain a value but is still able to observe, handle and recover an error state.Capturing exceptions
Opposed to other types, higher-order functions that transform this type take checked functions, or more precisely, lambdas or method references that may throw checked exceptions.We intentionally do not provide alternate methods that take unchecked functions (like
map
vsmapTry
). Instead we make it explicit on the API layer that exceptions are properly handled when transforming values. An exception will not escape the context of aTry
in these cases.Another reason for not providing unchecked variants is that Vavr's higher-order functions always take the most general argument type. Checked functions that may throw
Throwable
are more general than unchecked functions because unchecked exceptions are restricted to throw runtime exceptions.Higher-order functions that return a concrete value, like
getOrElseGet(Supplier)
andfold(Function, Function)
, will not handle exceptions when calling function arguments. The parameter types make this clear.Transforming a Try
Transformations that are focused on a successful state are: Transformations that are focused on a failed state are:failed()
- transforms a failure into a successmapFailure(CheckedFunction)
- transforms the cause of a failureorElse(Callable)
- performs another computation in the case of a failurerecover(Class, CheckedFunction)
- recovers a specific failure by providing an alternate valuerecoverWith(Class, CheckedFunction)
- recovers a specific failure by performing an alternate computation
Handling the state of a Try
Opposed to Java (seeOptional.ifPresent(Consumer)
), we are able to chain one or more of the following actions:Getting the value of a Try
At some point, we might need to operate on the unwrapped value of a Try. These are our options to reduce a successful or failed state to a value:fold(Function, Function)
- safe alternative to get()get()
- unsafe, throws in the case of a failuregetOrElse(Object)
getOrElseGet(Supplier)
getOrElseThrow(Function)
Try with resources
It is also possible to useTry
directly withAutoCloseable
resources:final Try<T> calc = Try.of(() -> { try (final ac1 = someAutoCloseable1(); ...; final acn = someAutoCloseableN()) { return doSth(ac1, ..., acn); } finally { doSth(); } });
- See Also:
- Serialized Form
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description <R,A>
Rcollect(java.util.stream.Collector<? super T,A,R> collector)
Collects the underlying value (if present) using the providedcollector
.abstract boolean
equals(java.lang.Object that)
Checks if thisTry
is equal to the given objecto
.Try<java.lang.Throwable>
failed()
Inverts thisTry
.static <T> Try<T>
failure(java.lang.Throwable exception)
Creates aTry.Failure
that contains the givenexception
.Try<T>
filter(CheckedPredicate<? super T> predicate)
Returnsthis
if this is a Failure or this is a Success and the value satisfies the predicate.<U> Try<U>
flatMap(CheckedFunction<? super T,? extends Try<? extends U>> mapper)
FlatMaps the value of a Success or returns a Failure.<U> U
fold(java.util.function.Function<? super java.lang.Throwable,? extends U> ifFailure, java.util.function.Function<? super T,? extends U> ifSuccess)
Folds either theFailure
or theSuccess
side of the Try value.abstract T
get()
Deprecated.Unsafe operation (but not marked for removal).abstract java.lang.Throwable
getCause()
Deprecated.Unsafe operation (but not marked for removal).T
getOrElse(T other)
Returns the underlying value if present, otherwiseother
.T
getOrElseGet(java.util.function.Supplier<? extends T> supplier)
Returns the underlying value if present, otherwise the result ofother.get()
.<X extends java.lang.Throwable>
TgetOrElseThrow(java.util.function.Function<? super java.lang.Throwable,? extends X> exceptionProvider)
Returns the underlying value if present, otherwise throws a user-specific exception.abstract int
hashCode()
Computes the hash of thisTry
.abstract boolean
isFailure()
Checks if this is a Failure.abstract boolean
isSuccess()
Checks if this is a Success.Iterator<T>
iterator()
Returns anIterator
that allows us to perform intermediate, sequential operations known from Vavr's collection library.<U> Try<U>
map(CheckedFunction<? super T,? extends U> mapper)
Runs the given checked function if this is aTry.Success
, passing the result of the current expression to it.Try<T>
mapFailure(CheckedFunction<? super java.lang.Throwable,? extends java.lang.Throwable> mapper)
Maps the cause to a new exception if this is aFailure
or returns this instance if this is aSuccess
.static <T> Try<T>
of(java.util.concurrent.Callable<? extends T> callable)
Creates a Try of a Callable.Try<T>
onFailure(java.util.function.Consumer<? super java.lang.Throwable> action)
Consumes the cause if this is aTry.Failure
.Try<T>
onSuccess(java.util.function.Consumer<? super T> action)
Consumes the value if this is aTry.Success
.Try<T>
orElse(java.util.concurrent.Callable<? extends Try<? extends T>> callable)
Returns thisTry
in the case of aSuccess
, otherwiseother.call()
.<X extends java.lang.Throwable>
Try<T>recover(java.lang.Class<X> exceptionType, CheckedFunction<? super X,? extends T> recoveryFunction)
Returnsthis
, if this is aSuccess
or this is aFailure
and the cause is not assignable fromcause.getClass()
.<X extends java.lang.Throwable>
Try<T>recoverWith(java.lang.Class<X> exceptionType, CheckedFunction<? super X,? extends Try<? extends T>> recoveryFunction)
Returnsthis
, if this is aSuccess
or this is aFailure
and the cause is not assignable fromcause.getClass()
.static Try<java.lang.Void>
run(CheckedRunnable runnable)
Runs aCheckedRunnable
and captures any non-fatal exception in aTry
.java.util.stream.Stream<T>
stream()
Converts thisTry
to aStream
.static <T> Try<T>
success(T value)
Creates aTry.Success
that contains the givenvalue
.<U> Either<U,T>
toEither(java.util.function.Function<? super java.lang.Throwable,? extends U> failureMapper)
Converts thisTry
to anEither
.Option<T>
toOption()
Converts thisTry
to anOption
.java.util.Optional<T>
toOptional()
Converts thisTry
to anOptional
.abstract java.lang.String
toString()
Returns a string representation of thisTry
.<U> Try<U>
transform(CheckedFunction<? super java.lang.Throwable,? extends Try<? extends U>> ifFailure, CheckedFunction<? super T,? extends Try<? extends U>> ifSuccess)
Transforms thisTry
by applying eitherifSuccess
to this value orifFailure
to this cause.
-
-
-
Method Detail
-
of
public static <T> Try<T> of(java.util.concurrent.Callable<? extends T> callable)
Creates a Try of a Callable.- Type Parameters:
T
- Component type- Parameters:
callable
- A supplier that may throw a checked exception- Returns:
Success(callable.call())
if no exception occurs, otherwiseFailure(cause)
if a non-fatal error occurs callingcallable.call()
.- Throws:
java.lang.Error
- if the cause of theTry.Failure
is fatal, i.e. non-recoverable
-
run
public static Try<java.lang.Void> run(CheckedRunnable runnable)
Runs aCheckedRunnable
and captures any non-fatal exception in aTry
.Because running a unit of work is all about performing side-effects rather than returning a value, a
Try<Void>
is created.- Parameters:
runnable
- A checked runnable, i.e. a runnable that may throw a checked exception.- Returns:
Success(null)
if no exception occurs, otherwiseFailure(throwable)
if an exception occurs callingrunnable.run()
.- Throws:
java.lang.Error
- if the cause of theTry.Failure
is fatal, i.e. non-recoverable
-
success
public static <T> Try<T> success(T value)
Creates aTry.Success
that contains the givenvalue
. Shortcut fornew Success<>(value)
.- Type Parameters:
T
- Type of the givenvalue
.- Parameters:
value
- A value.- Returns:
- A new
Success
.
-
failure
public static <T> Try<T> failure(java.lang.Throwable exception)
Creates aTry.Failure
that contains the givenexception
. Shortcut fornew Failure<>(exception)
.- Type Parameters:
T
- Component type of theTry
.- Parameters:
exception
- An exception.- Returns:
- A new
Failure
. - Throws:
java.lang.Error
- if the givenexception
is fatal, i.e. non-recoverable
-
collect
public <R,A> R collect(java.util.stream.Collector<? super T,A,R> collector)
Collects the underlying value (if present) using the providedcollector
.Shortcut for
.stream().collect(collector)
.- Type Parameters:
A
- the mutable accumulation type of the reduction operationR
- the result type of the reduction operation- Parameters:
collector
- Collector performing reduction- Returns:
- the reduction result of type
R
- Throws:
java.lang.NullPointerException
- if the givencollector
is null
-
failed
public Try<java.lang.Throwable> failed()
Inverts thisTry
.- Returns:
Success(throwable)
if this is aFailure(throwable)
, otherwise aFailure(new UnsupportedOperationException("Success.failed()"))
if this is aSuccess
.
-
filter
public Try<T> filter(CheckedPredicate<? super T> predicate)
Returnsthis
if this is a Failure or this is a Success and the value satisfies the predicate.Returns a new Failure, if this is a Success and the value does not satisfy the Predicate or an exception occurs testing the predicate. The returned Failure wraps a
NoSuchElementException
instance.- Parameters:
predicate
- A checked predicate- Returns:
- a
Try
instance - Throws:
java.lang.NullPointerException
- ifpredicate
is null
-
flatMap
public <U> Try<U> flatMap(CheckedFunction<? super T,? extends Try<? extends U>> mapper)
FlatMaps the value of a Success or returns a Failure.- Type Parameters:
U
- The new component type- Parameters:
mapper
- A mapper- Returns:
- a
Try
- Throws:
java.lang.NullPointerException
- ifmapper
is null
-
fold
public <U> U fold(java.util.function.Function<? super java.lang.Throwable,? extends U> ifFailure, java.util.function.Function<? super T,? extends U> ifSuccess)
Folds either theFailure
or theSuccess
side of the Try value.- Type Parameters:
U
- type of the folded value- Parameters:
ifFailure
- maps the cause if this is aFailure
ifSuccess
- maps the value if this is aSuccess
- Returns:
- A value of type U
- Throws:
java.lang.NullPointerException
- if one of the givenifFailure
orifSuccess
is null
-
get
@Deprecated public abstract T get() throws NonFatalException
Deprecated.Unsafe operation (but not marked for removal). Usefold(Function, Function)
,getOrElse(Object)
,getOrElseGet(Supplier)
orgetOrElseThrow(Function)
instead. Other alternatives areonSuccess(Consumer)
,Iterable.forEach(Consumer)
or iteration using a for-loop.Gets the result of this Try if this is aSuccess
or throws if this is aFailure
.If this is a
Failure
, it will throw cause wrapped in aNonFatalException
.- Returns:
- The computation result if this is a
Success
- Throws:
NonFatalException
- if this is aTry.Failure
-
getCause
@Deprecated public abstract java.lang.Throwable getCause() throws java.lang.UnsupportedOperationException
Deprecated.Unsafe operation (but not marked for removal). Usefold(Function, Function)
instead. An alternative isonFailure(Consumer)
.Gets the cause if this is a Failure or throws if this is a Success.- Returns:
- The cause if this is a Failure
- Throws:
java.lang.UnsupportedOperationException
- if this is a Success
-
getOrElse
public T getOrElse(T other)
Returns the underlying value if present, otherwiseother
.- Parameters:
other
- An alternative value.- Returns:
- A value of type
T
-
getOrElseGet
public T getOrElseGet(java.util.function.Supplier<? extends T> supplier)
Returns the underlying value if present, otherwise the result ofother.get()
.- Parameters:
supplier
- ASupplier
of an alternative value.- Returns:
- A value of type
T
- Throws:
java.lang.NullPointerException
- if the givenother
is null
-
getOrElseThrow
public <X extends java.lang.Throwable> T getOrElseThrow(java.util.function.Function<? super java.lang.Throwable,? extends X> exceptionProvider) throws X extends java.lang.Throwable
Returns the underlying value if present, otherwise throws a user-specific exception.- Type Parameters:
X
- exception type- Parameters:
exceptionProvider
- provides a user-specific exception- Returns:
- A value of type
T
- Throws:
X
- if this is aFailure
java.lang.NullPointerException
- if the givenexceptionProvider
is nullX extends java.lang.Throwable
-
isFailure
public abstract boolean isFailure()
Checks if this is a Failure.- Returns:
- true, if this is a Failure, otherwise false, if this is a Success
-
isSuccess
public abstract boolean isSuccess()
Checks if this is a Success.- Returns:
- true, if this is a Success, otherwise false, if this is a Failure
-
iterator
public Iterator<T> iterator()
Description copied from interface:Iterable
Returns anIterator
that allows us to perform intermediate, sequential operations known from Vavr's collection library.
-
map
public <U> Try<U> map(CheckedFunction<? super T,? extends U> mapper)
Runs the given checked function if this is aTry.Success
, passing the result of the current expression to it. If this expression is aTry.Failure
then it'll return a newTry.Failure
of type R with the original exception.The main use case is chaining checked functions using method references:
Try.of(() -> 0) .map(x -> 1 / x); // division by zero
- Type Parameters:
U
- The new component type- Parameters:
mapper
- A checked function- Returns:
- a
Try
- Throws:
java.lang.NullPointerException
- ifmapper
is null
-
mapFailure
public Try<T> mapFailure(CheckedFunction<? super java.lang.Throwable,? extends java.lang.Throwable> mapper)
Maps the cause to a new exception if this is aFailure
or returns this instance if this is aSuccess
.- Parameters:
mapper
- A function that maps the cause of a failure to another exception.- Returns:
- A new
Try
if this is aFailure
, otherwise this. - Throws:
java.lang.NullPointerException
- if the givenmapper
is null
-
onFailure
public Try<T> onFailure(java.util.function.Consumer<? super java.lang.Throwable> action)
Consumes the cause if this is aTry.Failure
.// (does not print anything) Try.success(1).onFailure(System.out::println); // prints "java.lang.Error" Try.failure(new Error()).onFailure(System.out::println);
- Parameters:
action
- An exception consumer- Returns:
- this
- Throws:
java.lang.NullPointerException
- ifaction
is null
-
onSuccess
public Try<T> onSuccess(java.util.function.Consumer<? super T> action)
Consumes the value if this is aTry.Success
.// prints "1" Try.success(1).onSuccess(System.out::println); // (does not print anything) Try.failure(new Error()).onSuccess(System.out::println);
- Parameters:
action
- A value consumer- Returns:
- this
- Throws:
java.lang.NullPointerException
- ifaction
is null
-
orElse
public Try<T> orElse(java.util.concurrent.Callable<? extends Try<? extends T>> callable)
Returns thisTry
in the case of aSuccess
, otherwiseother.call()
.- Parameters:
callable
- aCallable
- Returns:
- a
Try
instance
-
recover
public <X extends java.lang.Throwable> Try<T> recover(java.lang.Class<X> exceptionType, CheckedFunction<? super X,? extends T> recoveryFunction)
Returnsthis
, if this is aSuccess
or this is aFailure
and the cause is not assignable fromcause.getClass()
.Otherwise tries to recover the exception of the failure with
recoveryFunction
.// = Success(13) Try.of(() -> 27/2).recover(ArithmeticException.class, x -> Integer.MAX_VALUE); // = Success(2147483647) Try.of(() -> 1/0) .recover(Error.class, x -> -1) .recover(ArithmeticException.class, x -> Integer.MAX_VALUE); // = Failure(java.lang.ArithmeticException: / by zero) Try.of(() -> 1/0).recover(Error.class, x -> Integer.MAX_VALUE);
- Type Parameters:
X
- Exception type- Parameters:
exceptionType
- The specific exception type that should be handledrecoveryFunction
- A recovery function taking an exception of typeX
- Returns:
- a
Try
instance - Throws:
java.lang.NullPointerException
- ifexception
is null orrecoveryFunction
is null
-
recoverWith
public <X extends java.lang.Throwable> Try<T> recoverWith(java.lang.Class<X> exceptionType, CheckedFunction<? super X,? extends Try<? extends T>> recoveryFunction)
Returnsthis
, if this is aSuccess
or this is aFailure
and the cause is not assignable fromcause.getClass()
. Otherwise tries to recover the exception of the failure withrecoveryFunction
which returns Try. IfisFailure()
returned byrecoveryFunction
function istrue
it means that recovery cannot take place due to some circumstances.// = Success(13) Try.of(() -> 27/2).recoverWith(ArithmeticException.class, x -> Try.success(Integer.MAX_VALUE)); // = Success(2147483647) Try.of(() -> 1/0) .recoverWith(Error.class, x -> Try.success(-1)) .recoverWith(ArithmeticException.class, x -> Try.success(Integer.MAX_VALUE)); // = Failure(java.lang.ArithmeticException: / by zero) Try.of(() -> 1/0).recoverWith(Error.class, x -> Try.success(Integer.MAX_VALUE));
- Type Parameters:
X
- Exception type- Parameters:
exceptionType
- The specific exception type that should be handledrecoveryFunction
- A recovery function taking an exception of typeX
and returning Try as a result of recovery. If Try isisSuccess()
then recovery ends up successfully. Otherwise the function was not able to recover.- Returns:
- a
Try
instance - Throws:
java.lang.NullPointerException
- ifexceptionType
orrecoveryFunction
is nulljava.lang.Error
- if the given recovery functionrecoveryFunction
throws a fatal error
-
stream
public java.util.stream.Stream<T> stream()
Converts thisTry
to aStream
.- Returns:
Stream.of(get()
if this is a success, otherwiseStream.empty()
-
toEither
public <U> Either<U,T> toEither(java.util.function.Function<? super java.lang.Throwable,? extends U> failureMapper)
Converts thisTry
to anEither
.- Type Parameters:
U
- the left type of theEither
- Parameters:
failureMapper
- a failure mapper- Returns:
Either.right(get()
if this is a success, otherwiseEither.left(failureMapper.apply(getCause())
- Throws:
java.lang.NullPointerException
- if the givenfailureMapper
is null
-
toOption
public Option<T> toOption()
Converts thisTry
to anOption
.- Returns:
Option.some(get()
if this is a success, otherwiseOption.none()
-
toOptional
public java.util.Optional<T> toOptional()
Converts thisTry
to anOptional
.- Returns:
Optional.ofNullable(get())
if this is a success, otherwiseOptional.empty()
-
transform
public <U> Try<U> transform(CheckedFunction<? super java.lang.Throwable,? extends Try<? extends U>> ifFailure, CheckedFunction<? super T,? extends Try<? extends U>> ifSuccess)
Transforms thisTry
by applying eitherifSuccess
to this value orifFailure
to this cause.- Type Parameters:
U
- type of the transformed value- Parameters:
ifFailure
- maps the cause if this is aFailure
ifSuccess
- maps the value if this is aSuccess
- Returns:
- A new
Try
instance - Throws:
java.lang.NullPointerException
- if one of the givenifSuccess
orifFailure
is null
-
equals
public abstract boolean equals(java.lang.Object that)
Checks if thisTry
is equal to the given objecto
.- Overrides:
equals
in classjava.lang.Object
- Parameters:
that
- an object, may be null- Returns:
- true, if
this
andthat
both are a success and the underlying values are equal or ifthis
andthat
both are a failure and the underlying causes refer to the same object. Otherwise it returns false.
-
hashCode
public abstract int hashCode()
Computes the hash of thisTry
.- Overrides:
hashCode
in classjava.lang.Object
- Returns:
31 + Objects.hashCode(get())
if this is a success, otherwiseObjects.hashCode(getCause())
-
toString
public abstract java.lang.String toString()
Returns a string representation of thisTry
.- Overrides:
toString
in classjava.lang.Object
- Returns:
"Success(" + get() + ")"
if this is a success, otherwise"Failure(" + getCause() + ")"
-
-