@@ -982,6 +982,62 @@ default Try<T> recoverWith(Function<? super Throwable, ? extends Try<? extends T
982
982
}
983
983
}
984
984
985
+ /**
986
+ * Returns {@code this}, if this is a {@link Try.Success}, otherwise attempts to recover from any failure
987
+ * by evaluating the given {@code recoveryAttempt} (via {@link Try#of(CheckedFunction0)}).
988
+ *
989
+ * <pre>{@code
990
+ * // = Success(5)
991
+ * Try.of(() -> 5)
992
+ * .recoverAllAndTry(() -> 10);
993
+ *
994
+ * // = Success(10)
995
+ * Try.of(() -> 1/0)
996
+ * .recoverAllAndTry(() -> 10);
997
+ * }</pre>
998
+ *
999
+ * @param recoveryAttempt A checked function that provides a fallback in case of a failure
1000
+ * @return a {@code Try} that is either this {@code Success} or a new {@code Try} evaluated from {@code recoveryAttempt}
1001
+ * @throws NullPointerException if {@code recoveryAttempt} is null
1002
+ */
1003
+ default Try <T > recoverAllAndTry (CheckedFunction0 <? extends T > recoveryAttempt ) {
1004
+ Objects .requireNonNull (recoveryAttempt , "recoveryAttempt is null" );
1005
+ return isFailure () ? of (recoveryAttempt ) : this ;
1006
+ }
1007
+
1008
+ /**
1009
+ * Returns {@code this}, if this is a {@link Try.Success}, otherwise attempts to recover from failure when the
1010
+ * underlying cause is assignable to the specified {@code exceptionType}, by evaluating the given
1011
+ * {@code recoveryAttempt} (via {@link Try#of(CheckedFunction0)}).
1012
+ *
1013
+ * <pre>{@code
1014
+ * // = Success(5)
1015
+ * Try.of(() -> 5)
1016
+ * .recoverAndTry(ArithmeticException.class, () -> 10);
1017
+ *
1018
+ * // = Success(10)
1019
+ * Try.of(() -> 1/0)
1020
+ * .recoverAndTry(ArithmeticException.class, () -> 10);
1021
+ *
1022
+ * // = Failure(java.lang.ArithmeticException: / by zero)
1023
+ * Try.of(() -> 1/0)
1024
+ * .recoverAndTry(NullPointerException.class, () -> 10);
1025
+ * }</pre>
1026
+ *
1027
+ * @param <X> The type of the exception that may be recovered
1028
+ * @param exceptionType The specific exception type that should trigger the recovery
1029
+ * @param recoveryAttempt A checked function that provides a fallback in case of a matching failure
1030
+ * @return a {@code Try} that is either this {@code Success}, or a new {@code Try} evaluated from {@code recoveryAttempt}
1031
+ * @throws NullPointerException if {@code exceptionType} or {@code recoveryAttempt} is null
1032
+ */
1033
+ default <X extends Throwable > Try <T > recoverAndTry (Class <X > exceptionType , CheckedFunction0 <? extends T > recoveryAttempt ) {
1034
+ Objects .requireNonNull (exceptionType , "exceptionType is null" );
1035
+ Objects .requireNonNull (recoveryAttempt , "recoveryAttempt is null" );
1036
+ return isFailure () && exceptionType .isAssignableFrom (getCause ().getClass ())
1037
+ ? of (recoveryAttempt )
1038
+ : this ;
1039
+ }
1040
+
985
1041
/**
986
1042
* Converts this {@code Try} to an {@link Either}.
987
1043
*
0 commit comments