feat: Add sneakyThrow for Java (#2218)
This commit is contained in:
parent
3969ae8276
commit
9b5e641246
2 changed files with 20 additions and 0 deletions
|
|
@ -29,4 +29,13 @@ public class ThrowablesTest {
|
||||||
Assert.assertTrue(Throwables.isFatal(new InterruptedException("fatal")));
|
Assert.assertTrue(Throwables.isFatal(new InterruptedException("fatal")));
|
||||||
Assert.assertTrue(Throwables.isFatal(new LinkageError("fatal")));
|
Assert.assertTrue(Throwables.isFatal(new LinkageError("fatal")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void doSneakyThrow() {
|
||||||
|
Throwables.sneakyThrow(new Exception("sneaky"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSneakyThrow() {
|
||||||
|
Assert.assertThrows("sneaky", Exception.class, this::doSneakyThrow);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -49,4 +49,15 @@ object Throwables {
|
||||||
* or false if it is to be considered non-fatal
|
* or false if it is to be considered non-fatal
|
||||||
*/
|
*/
|
||||||
def isFatal(throwable: Throwable): Boolean = !isNonFatal(throwable)
|
def isFatal(throwable: Throwable): Boolean = !isNonFatal(throwable)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws the given `Throwable`, without requiring the caller to declare it in a `throws` clause.
|
||||||
|
* @param t the `Throwable` to throw
|
||||||
|
* @throws T the type of the `Throwable` to throw
|
||||||
|
* @return never returns normally, but has return type `R` to allow usage in expressions
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
def sneakyThrow[T <: Throwable, R](t: Throwable): R = {
|
||||||
|
throw t.asInstanceOf[T]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue