Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are there any differences between Checked and Unchecked Exceptions at Runtime?

Checked Exceptions are powerful because they allow you to force the use-site to deal with an exceptional case. If the use-site does not handle an exceptional case (or publically announce that they are not handling it), then the code will fail to compile.

However, that’s compile time. What about Runtime?

Are their any meaningful differences between Checked and Unchecked Exceptions at Runtime?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The only thing I can think of is that Unchecked Exceptions extend RuntimeException, but I don’t see any properties about RuntimeException that would allow it to be treated differently at RUNTIME.

>Solution :

Checked exceptions are a feature of the Java language and only enforced by the compiler. They are not enforced by the Java virtual machine whatsoever.

In fact, with some abuse of generics, you can throw any exception you want, from wherever you want:

class Example {
    public static void sneakyThrow(Throwable t) {
        Example.<RuntimeException>sneakyThrow0(t);
    }
    
    @SuppressWarnings("unchecked")
    private static <T extends Throwable> void sneakyThrow0(Throwable t) throws T {
        throw (T)t;
    }
    
    public static void main(String[] args) {
        sneakyThrow(new IOException());
    }
}

Output:

Exception in thread "main" java.io.IOException
    at Example.main(Example.java:12)

Also, the reflection method Class.newInstance() is deprecated because due to a design flaw, it rethrows any checked exception thrown by the class’s constructor, without wrapping or declaring it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading