Search code examples
javaexceptioncheckedunchecked

Throwing checked exception as unchecked. Is there any way to prevent in runtime?


With the simplified code I can throw Checked Exception without catching (the same way as uncheked). From javadoc about RuntimeException - Compile-Time Checking of Exceptions. Is there any way to prevent the behavior in runtime?

import java.io.IOException;

public class TestException {

    static <E extends Exception>

    void doThrow(final Exception e) throws E {
        throw (E) e;
    }

    public static void main(String[] args) {
        TestException.<RuntimeException>doThrow(
              new IOException("Checked exception thrown")
        );
    }

}

Solution

  • Yes, correct the method signature to:

    static <E extends Exception> void doThrow(final E e) throws E {
        throw e;
    }