
name.remal.SneakyThrow Maven / Gradle / Ivy
package name.remal;
import name.remal.gradle_plugins.api.ExcludeFromCodeCoverage;
import org.jetbrains.annotations.NotNull;
@ExcludeFromCodeCoverage
public class SneakyThrow {
/**
* Throws any throwable 'sneakily' - you don't need to catch it, nor declare that you throw it onwards.
* The exception is still thrown - javac will just stop whining about it.
*
* Example usage:
*
public void run() {
* throw sneakyThrow(new IOException("You don't need to catch me!"));
* }
*
* NB: The exception is not wrapped, ignored, swallowed, or redefined. The JVM actually does not know or care
* about the concept of a 'checked exception'. All this method does is hide the act of throwing a checked exception
* from the java compiler.
*
* Note that this method has a return type of {@code RuntimeException}; it is advised you always call this
* method as argument to the {@code throw} statement to avoid compiler errors regarding no return
* statement and similar problems. This method won't of course return an actual {@code RuntimeException} -
* it never returns, it always throws the provided exception.
*
* @param t The throwable to throw without requiring you to catch its type.
* @return A dummy RuntimeException; this method never returns normally, it always throws an exception!
*/
@NotNull
public static RuntimeException sneakyThrow(@NotNull Throwable t) {
SneakyThrow.sneakyThrow0(t);
return null;
}
@SuppressWarnings("unchecked")
private static void sneakyThrow0(Throwable t) throws T {
throw (T) t;
}
}