Interface Try<T>

  • Type Parameters:
    T - the type of entity contained

    public interface Try<T>

    The try interface allows for easier and more functional coding around exception handling. This interface allows for conditionally running a operation chain. The chain will continue to be executed for as long as there is no exception. As soon as an exception occurs the chain will be short-circuited and the resulting Try will contain an isFailure() and the underlying getCause().

    The Try can be used like the example below, to either recover from an exception or gracefully catch one.

    Example:

     String result = Try<String>supply(() -> {
              throw new Exception("not supported");
            })
            .recover(x -> "recovered")
            .get();
     
    Since:
    0.0.2
    • Method Summary

      All Methods Instance Methods Abstract Methods Default Methods 
      Modifier and Type Method Description
      default Try<T> consume​(CheckedConsumer<? super T> consumer)
      Passes then entity contained within the get() if the try has a success.
      T get()
      Get the value contained in the try.
      java.lang.Throwable getCause()
      Return the cause of the failure.
      boolean isFailure()
      Indicates if the try operation resulted in an exception
      boolean isSuccess()
      Indicates if the try operation was successful
      default <U> Try<U> map​(java.util.function.Function<T,​U> mapper)  
      <X extends java.lang.Throwable>
      Try<T>
      recover​(java.util.function.Function<X,​T> recoverMethod)
      Set a fallback operation to be executed when the primary operation fails.
      default Try<T> run​(CheckedRunner runner)
      Allows for secondary runners to be executed within a try..catch.
    • Method Detail

      • consume

        default Try<T> consume​(CheckedConsumer<? super T> consumer)
        Passes then entity contained within the get() if the try has a success. Otherwise it will not call the consumer and return the try containing the failure.

        This method exists for chaining checked functions, like:

         Try.of(() -> "my success")
             .andTry( str -> System.out.println(str));
         
        Parameters:
        consumer - the checked consumer to consume the value contained within
        Returns:
        a Try with isSuccess() is true in case of no issues, otherwise a Try with isFailure() is true.
        Throws:
        java.lang.NullPointerException - in case the consumer is null
      • get

        T get()
        Get the value contained in the try. This method will throw an exception in case the try failed somewhere in the chain. Use isFailure() to detect if a failure occurred.
        Returns:
        the value contained
      • getCause

        java.lang.Throwable getCause()
        Return the cause of the failure. If the isSuccess() is true this call will cause an exception.
        Returns:
        get the root cause for a failure
      • isFailure

        boolean isFailure()
        Indicates if the try operation resulted in an exception
        Returns:
        true in case of an exception of the try, otherwise false
      • isSuccess

        boolean isSuccess()
        Indicates if the try operation was successful
        Returns:
        false in case of an exception of the try, otherwise true
      • map

        default <U> Try<U> map​(java.util.function.Function<T,​U> mapper)
      • recover

        <X extends java.lang.Throwable> Try<T> recover​(java.util.function.Function<X,​T> recoverMethod)

        Set a fallback operation to be executed when the primary operation fails.

        Example:

        List<String> safeGet = Try.supply(myDatabase::getRecords)
                  .recover(x -> Collections.emptyList())
                  .get();
         

        In the sample above a call is made to a database repository, which can fail with various exceptions. In case the call fails then the logic in the recover operation is executed instead. The result of this logic will be returned to the caller. In the case of the example the caller will get an empty list when the database call fails.

        Type Parameters:
        X - the type of exception thrown by the primary operation
        Parameters:
        recoverMethod - the operation that will be executed when the primary operation fails
        Returns:
        the result of the recoverMethod operation
      • run

        default Try<T> run​(CheckedRunner runner)
        Allows for secondary runners to be executed within a try..catch. If the runner does not throw any exceptions then this method will return the current Try instance. Otherwise it will return a Try with isFailure() returning true.

        This method allows for chaining multiple logical execution blocks that need to run sequential as long as there are no exceptions.

        Example:

         Try.of(() -> System.out.println("first") )
             .andTry(() -> System.out.println("second"));
         
        Parameters:
        runner - the part of code that should be executed, wrapped in a CheckedRunner
        Returns:
        Try with isSuccess() is true in case of no issues, otherwise a Try with isFailure() is true.
        Throws:
        java.lang.NullPointerException - in case the runner is null