Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 there any meaningful differences between Checked and Unchecked Exceptions at Runtime?

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.

like image 451
davidalayachew Avatar asked May 11 '26 18:05

davidalayachew


2 Answers

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.

The throws clause is still recorded in a compiled class file for sake of programming against a compiled library. But in describing the meaning of the data, the JVM spec notes that:

These requirements are not enforced in the Java Virtual Machine; they are enforced only at compile time.

There are various ways to bypass exception checking, such as by abusing generics (which are erased at run time and not fully checked):

class Example {
    public static void main(String[] args) {
        sneakyThrow(new java.io.IOException());
    }
    
    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;
    }
}

Output:

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

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:

Deprecated.
This method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.

like image 74
Boann Avatar answered May 14 '26 08:05

Boann


I don't think the JVM makes a distinction between it. The try-with-resources statement, for example, actually creates a throw Throwable statement by the Java compiler.

[2025/1/15] java compiler doesn't create the throw statement. It creates the 'ATHROW' bytecode with a java.lang.Throwable object.

like image 37
xia__mc Avatar answered May 14 '26 08:05

xia__mc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!