feat: Add sneakyThrow for Java (#2218)

This commit is contained in:
He-Pin(kerr) 2025-09-19 22:44:53 +08:00 committed by GitHub
parent 3969ae8276
commit 9b5e641246
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 0 deletions

View file

@ -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);
}
} }

View file

@ -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]
}
} }