Class Throwables


  • public final class Throwables
    extends Object
    • Method Detail

      • getRootCause

        public static Throwable getRootCause​(Throwable throwable)
        Returns the innermost cause of throwable. The first throwable in a chain provides context from when the error or exception was initially detected. Example usage:

         assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
         
      • throwIfUnchecked

        public static void throwIfUnchecked​(Throwable throwable)
        Throws throwable if it is a RuntimeException or Error. Example usage:

         for (Foo foo : foos) {
           try {
             foo.bar();
           } catch (RuntimeException | Error t) {
             failure = t;
           }
         }
         if (failure != null) {
           throwIfUnchecked(failure);
           throw new AssertionError(failure);
         }
         
        Since:
        20.0
      • rethrow

        public static <T> Consumer<T> rethrow​(Throwables.ThrowingConsumer<T> consumer)
        Provides a consumer that helps in rethrowing checked exception for lambdas. Example:
             foo.bar( rethrow( param -> param.doSomething() ) )
         

        If doSomething() throws a checked exception, compiler will allow it even if it's not wrapped in a try-catch block. The exception can be optionally caught using a try-catch block. Example:
             try {
                 foo.bar( rethrow( param -> param.doSomething() ) )
             } catch ( Exception e ) {
                 // Exception can be caught here
             }
         
      • rethrowFunction

        public static <T,​R> Function<T,​R> rethrowFunction​(Throwables.ThrowingFunction<T,​R> function)
        Provides a function that helps in rethrowing checked exception for lambdas. Example:
             foo.bar( rethrow( param -> param.returnSomething() ) )
         

        If doSomething() throws a checked exception, compiler will allow it even if it's not wrapped in a try-catch block. The exception can be optionally caught using a try-catch block. Example:
             try {
                 foo.bar( rethrow( param -> param.returnSomething() ) )
             } catch ( Exception e ) {
                 // Exception can be caught here
             }
         
      • functionSneakyThrow

        public static <E extends Throwable,​R> R functionSneakyThrow​(Throwable ex)
                                                                   throws E extends Throwable
        Allows transforming of checked exceptions to unchecked. The compiler sees the signature with the throws T inferred to a RuntimeException type, so it allows the unchecked exception to propagate.
        Throws:
        E extends Throwable