public class Try<R>
extends java.lang.Object
Use methods: run(DangerousRunnable), perform(DangerousSupplier),
or withResource(DangerousSupplier, DangerousFunction) to create instance of the class that will contain
either result of the code execution, or the exception thrown in the process of execution.
Methods #perform and #withResource intercept instances of Exception and created instance of the Try
allows you to perform operations on either outcome in a functional matter.
Note: only Exception instances are caught. Any Errors will fall thru.
| Modifier and Type | Method and Description |
|---|---|
Try<R> |
assertFail(org.hamcrest.Matcher<? super java.lang.Exception> matcher)
If this try is not successful -
Assert.assertThat(Object, Matcher) is called
with the specified matcher. |
Try<R> |
assertFail(org.hamcrest.Matcher<? super java.lang.Exception> matcher,
java.lang.String message)
If this try is not successful -
Assert.assertThat(Object, Matcher, String) is called
with the specified matcher and message. |
Try<R> |
assertFailIsInstanceOf(java.lang.Class<? extends java.lang.Exception> type)
If this try is not successful - check its cause is an instance of the specified class.
|
Try<R> |
assertFailIsInstanceOf(java.lang.Class<? extends java.lang.Exception> type,
java.lang.String message)
If this try is not successful - check its cause is an instance of the specified class.
|
Try<R> |
assertFailNotExpected()
If this try is not successful - throw an
AssertError about its cause. |
Try<R> |
assertFailNotExpected(java.lang.String message)
If this try is not successful - throw an
AssertError about its cause. |
java.lang.Exception |
getCause() |
java.util.Optional<R> |
getOptionalResult()
Similar to using
getResult() with Optional.ofNullable(Object). |
R |
getOrElse(R inCaseOfFail)
Method returns result of the try, if perform were successful, or specified value.
|
R |
getResult()
Get result of the safe execution.
|
java.lang.Throwable |
getSuppressed()
Any exception thrown from
AutoCloseable.close() method of a resource used in
the withResource(DangerousSupplier, DangerousFunction) method. |
boolean |
isCaught() |
boolean |
isSuccess() |
Try<R> |
onAnyResult(java.util.function.BiConsumer<R,java.lang.Exception> consumer)
Perform some operation in any case of success or fail.
|
Try<R> |
onPerformFail(java.util.function.Consumer<java.lang.Exception> consumer) |
<T extends java.lang.Exception,E extends java.lang.Exception> |
onPerformFailCatch(java.lang.Class<T> type,
DangerousConsumer<T,E> consumer)
If result of the
getCause() method is instance of the specified class - calls specified consumer
with exception cast to the caught type. |
<E extends java.lang.Exception> |
onPerformFailDangerous(DangerousConsumer<java.lang.Exception,E> consumer) |
Try<R> |
onPerformFailRethrow()
If this try is not successful - throws result of the
getCause() method. |
<T extends java.lang.Throwable> |
onPerformFailThrow(java.util.function.Function<java.lang.Exception,T> function)
If this Try is not successful - applies specified mapper to the result of
getCause() method and then
throws result of the function. |
Try<R> |
onPerformSuccess(java.util.function.Consumer<R> consumer)
Specified consumer is called only if this try is successful.
|
<V> Try<V> |
onPerformSuccessTry(DangerousFunction<R,V,java.lang.Exception> mapper)
If execution of this try has finished successfully - applies specified dangerous mapper function to the result
and return new instance of a Try with result of the function.
|
<Res extends java.lang.AutoCloseable,V> |
onPerformSuccessTryWithResource(DangerousSupplier<Res,java.lang.Exception> resourceSupplier,
DangerousBiFunction<Res,R,V,java.lang.Exception> mapper)
If execution of this try has finished successfully - calls specified resource supplier to receive resource,
and then applies specified mapper bifunction to the resource and the result of this try.
|
static <R> Try<R> |
perform(DangerousSupplier<R,java.lang.Exception> code)
Perform a chunk of code that returns some value and store this value if execution finished successfully.
|
static Try<java.lang.Void> |
run(DangerousRunnable<java.lang.Exception> code)
Perform a chunk of code in a safe manner.
|
java.lang.String |
toString() |
static <Res extends java.lang.AutoCloseable,R> |
withResource(DangerousSupplier<Res,java.lang.Exception> resourceSupplier,
DangerousFunction<Res,R,java.lang.Exception> code)
Simulate try-with-resource functionality.
|
public static Try<java.lang.Void> run(DangerousRunnable<java.lang.Exception> code)
Void and alwaus
will have null as result.public static <R> Try<R> perform(DangerousSupplier<R,java.lang.Exception> code)
public static <Res extends java.lang.AutoCloseable,R> Try<R> withResource(DangerousSupplier<Res,java.lang.Exception> resourceSupplier, DangerousFunction<Res,R,java.lang.Exception> code)
Simulate try-with-resource functionality. Specified resource supplier can produce any resource of the type
AutoCloseable. If resource was supplied successfully - specified function is applied to it.
Result instance will contain either result of the function, or thrown exception.
Note: any throwable thrown from the AutoCloseable.close() method of the resource will
be stored as 'suppressed', and might be accessed by getSuppressed() method. If function finished
successfully, but resource failed to close - result instance will contain both result and 'suppressed'
error - and will be treated as successful.
public R getResult()
Get result of the safe execution.
Note: result might be null in case of successful execution. Either if runnable were executed
(then type of this instance is Void, and nothing but null is possible as result), or
executed code finished successfully, but returned null as result;
Only isSuccess() method provides definite indication whether try was performed successfully.
public java.util.Optional<R> getOptionalResult()
getResult() with Optional.ofNullable(Object).
Created for better usability in functional style.public R getOrElse(R inCaseOfFail)
Method returns result of the try, if perform were successful, or specified value.
Note: seemingly similar to Optional.orElse(Object) this method might return null
if execution finished successfully, but returned null. For example, if runnable were executed successfully
result will always be null.
If you want to achieve functionality similar to Optional - use getOptionalResult()
public java.lang.Exception getCause()
public java.lang.Throwable getSuppressed()
Any exception thrown from AutoCloseable.close() method of a resource used in
the withResource(DangerousSupplier, DangerousFunction) method.
Note: presence if this throwable does not affect success status of the try.
public boolean isSuccess()
public boolean isCaught()
public Try<R> onAnyResult(java.util.function.BiConsumer<R,java.lang.Exception> consumer)
null.
In some cases both arguments might be null (if execution finished successfully, but returned null)public Try<R> onPerformSuccess(java.util.function.Consumer<R> consumer)
Specified consumer is called only if this try is successful.
Note: result accepted by the consumer might be null, if execution finished successfully,
but returned null.
public <V> Try<V> onPerformSuccessTry(DangerousFunction<R,V,java.lang.Exception> mapper)
If execution of this try has finished successfully - applies specified dangerous mapper function to the result and return new instance of a Try with result of the function. If this Try is not successful - new instance contains the same cause and suppressed error.
Equivalent of:
Try t = Try.perform(code);
if (t.isSuccess())
t = Try.perform(() -> mapper.apply(t.getResult()));
public <Res extends java.lang.AutoCloseable,V> Try<V> onPerformSuccessTryWithResource(DangerousSupplier<Res,java.lang.Exception> resourceSupplier, DangerousBiFunction<Res,R,V,java.lang.Exception> mapper)
If execution of this try has finished successfully - calls specified resource supplier to receive resource, and then applies specified mapper bifunction to the resource and the result of this try. Then new instance of a Try returned with the result of this mapper bifunction. If this Try is not successful - new instance contains the same cause and suppressed error.
Equivalent of:
Try t = try.perform(code);
if (t.isSuccess())
t = Try.withResource(resourceSupplier, res -> mapper.apply(res, t.getResult()));
public Try<R> onPerformFail(java.util.function.Consumer<java.lang.Exception> consumer)
public <E extends java.lang.Exception> Try<R> onPerformFailDangerous(DangerousConsumer<java.lang.Exception,E> consumer) throws E extends java.lang.Exception
E extends java.lang.Exceptionpublic <T extends java.lang.Throwable> Try<R> onPerformFailThrow(java.util.function.Function<java.lang.Exception,T> function) throws T extends java.lang.Throwable
If this Try is not successful - applies specified mapper to the result of getCause() method and then
throws result of the function.
T extends java.lang.Throwablepublic Try<R> onPerformFailRethrow() throws java.lang.Exception
If this try is not successful - throws result of the getCause() method.
java.lang.Exceptionpublic <T extends java.lang.Exception,E extends java.lang.Exception> Try<R> onPerformFailCatch(java.lang.Class<T> type, DangerousConsumer<T,E> consumer) throws E extends java.lang.Exception
If result of the getCause() method is instance of the specified class - calls specified consumer
with exception cast to the caught type.
Note: exception can be caught only once! If one of the blocks caught the exception - later blocks
will not be called! Even though the other methods, like onPerformFail(Consumer) still will be called.
Example:
Try.perform(() -> {throw new IOException()})
.onPerformFailCatch(FileNotFoundException.class, (FileNotFoundException e) -> {
System.out.println("This is not called");
})
.onPerformFailCatch(IOException.class, (IOException e) -> {
System.out.println("This one is called");
})
.onPerformFailCatch(Exception.class, (Exception e) -> {
System.out.println("This one is not called");
})
.onPerformFail((Exception e) -> {
System.out.println("Though this one is called");
});
Note: exception can be caught once even with retry. It means that if your initial try was not
successful, and you've caught the cause - and then you performed onPerformSuccessTry(DangerousFunction)
or onPerformSuccessTryWithResource(DangerousSupplier, DangerousBiFunction) - you have created new
instance of a Try, but its cause still marked as caught. Example:
Try t = Try.perform(() -> {throw new IOException()});
t.onPerformFailCatch(Exception.class, (Exception e) -> {
System.out.println("This one is called");
});
Try t2 = t.onPerformSuccessTry(x -> 42);
assert t2 != t; // true
assert t2.getCause() == t.getCause(); // true
t2.onPerformFailCatch(Exception.class, (Exception e) -> {
System.out.println("This one is NOT called");
});
But NOT caught exceptions are marked as NOT caught even after retry. Example:
Try.perform(() -> {throw new IOException()})
.onPerformSuccessTry(x -> {throw new RuntimeException()})
.onPerformFailCatch(IOException.class, (IOException e) -> {
System.out.println("This one IS called");
});
Note: the same exception can be caught twice, if retry was created before catch, and then catch is performed on both instances. Example:
Try t = Try.perform(() -> {throw new IOException()});
Try t2 = t.onPerformSuccessTry(x -> 42);
t.onPerformFailCatch(Exception.class, (Exception e) -> {
System.out.println("This one IS called");
});
t2.onPerformFailCatch(Exception.class, (Exception e) -> {
System.out.println("This one IS also called");
});
So you can break 'functional' style, but preserve 'uncaught' state even after retry. This is specifically implemented for any rare situations, when you need to reuse first Try even after retry was created and caught. Though, such use is not recommended.
E extends java.lang.Exceptionpublic Try<R> assertFail(org.hamcrest.Matcher<? super java.lang.Exception> matcher)
Assert.assertThat(Object, Matcher) is called
with the specified matcher. Any errors evoked by the assert are rethrown directly.assertFail(Matcher, String)public Try<R> assertFail(org.hamcrest.Matcher<? super java.lang.Exception> matcher, java.lang.String message)
Assert.assertThat(Object, Matcher, String) is called
with the specified matcher and message. Any errors evoked by the assert are rethrown directly.assertFail(Matcher)public Try<R> assertFailNotExpected()
AssertError about its cause. Equivalent to:assertFailNotExpected(String)public Try<R> assertFailNotExpected(java.lang.String message)
AssertError about its cause. Equivalent to:assertFailNotExpected()public Try<R> assertFailIsInstanceOf(java.lang.Class<? extends java.lang.Exception> type)
assertFailIsInstanceOf(Class, String)public Try<R> assertFailIsInstanceOf(java.lang.Class<? extends java.lang.Exception> type, java.lang.String message)
assertFailIsInstanceOf(Class)public java.lang.String toString()
toString in class java.lang.Object