Is there a way to throw an exception without adding the throws declaration?

Here is a trick:

class Utils
{
    @SuppressWarnings("unchecked")
    private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
    {
        throw (T) exception;
    }

    public static void throwException(Throwable exception)
    {
        Utils.<RuntimeException>throwException(exception, null);
    }
}

public class Test
{
    public static void main(String[] args)
    {
        Utils.throwException(new Exception("This is an exception!"));
    }
}

A third option is to opt out of exception checking (just like the Standard API itself has to do sometimes) and wrap the checked exception in a RuntimeException:

throw new RuntimeException(originalException);

You may want to use a more specific subclass of RuntimeException.


You can throw unchecked exceptions without having to declare them if you really want to. Unchecked exceptions extend RuntimeException. Throwables that extend Error are also unchecked, but should only be used for completely un-handleable issues (such as invalid bytecode or out of memory).

As a specific case, Java 8 added UncheckedIOException for wrapping and rethrowing IOException.