add guava throwables example (#8984)

Co-authored-by: Mihai Lepadat <mihai.lepadat@irian.at>
This commit is contained in:
Mihai238 2020-03-30 22:59:12 +02:00 committed by GitHub
parent 8bfb7df3b2
commit 2d5782d432
1 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,44 @@
package com.baeldung.guava;
import com.google.common.base.Throwables;
import org.junit.Test;
import java.util.function.Supplier;
public class ThrowablesUnitTest {
@Test(expected = RuntimeException.class)
public void whenThrowable_shouldWrapItInRuntimeException() throws Exception {
try {
throwThrowable(Throwable::new);
} catch (Throwable t) {
Throwables.propagateIfPossible(t, Exception.class);
throw new RuntimeException(t);
}
}
@Test(expected = Error.class)
public void whenError_shouldPropagateAsIs() throws Exception {
try {
throwThrowable(Error::new);
} catch (Throwable t) {
Throwables.propagateIfPossible(t, Exception.class);
throw new RuntimeException(t);
}
}
@Test(expected = Exception.class)
public void whenException_shouldPropagateAsIs() throws Exception {
try {
throwThrowable(Exception::new);
} catch (Throwable t) {
Throwables.propagateIfPossible(t, Exception.class);
throw new RuntimeException(t);
}
}
private <T extends Throwable> void throwThrowable(Supplier<T> exceptionSupplier) throws Throwable {
throw exceptionSupplier.get();
}
}