public final class Throwables extends Object
Modifier and Type | Class and Description |
---|---|
static interface |
Throwables.ThrowingConsumer<T>
Taken from https://gist.github.com/myui/9722c1301434a3b69cf898ccd9090ff1.
|
static interface |
Throwables.ThrowingFunction<T,R>
|
Modifier and Type | Method and Description |
---|---|
static <E extends Throwable,R> |
functionSneakyThrow(Throwable ex)
Allows transforming of checked exceptions to unchecked.
|
static Throwable |
getRootCause(Throwable throwable)
Returns the innermost cause of
throwable . |
static <T> Consumer<T> |
rethrow(Throwables.ThrowingConsumer<T> consumer)
Provides a consumer that helps in rethrowing checked exception for lambdas.
|
static <T,R> Function<T,R> |
rethrowFunction(Throwables.ThrowingFunction<T,R> function)
Provides a function that helps in rethrowing checked exception for lambdas.
|
static <E extends Throwable> |
sneakyThrow(Throwable ex)
Allows transforming of checked exceptions to unchecked.
|
static void |
throwIfUnchecked(Throwable throwable)
|
public static Throwable getRootCause(Throwable throwable)
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());
public static void throwIfUnchecked(Throwable throwable)
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); }
public static <T> Consumer<T> rethrow(Throwables.ThrowingConsumer<T> consumer)
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 }
public static <E extends Throwable> void sneakyThrow(Throwable ex) throws E extends Throwable
E extends Throwable
public static <T,R> Function<T,R> rethrowFunction(Throwables.ThrowingFunction<T,R> function)
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 }
public static <E extends Throwable,R> R functionSneakyThrow(Throwable ex) throws E extends Throwable
E extends Throwable
Copyright © 2020. All rights reserved.