Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat parts of the JLS justify being able to throw checked exceptions as if they were unchecked?
    primarykey
    data
    text
    <p>I have <a href="http://java.dzone.com/articles/throw-checked-exceptions">recently discovered and blogged about the fact</a> that it is possible to sneak a checked exception through the javac compiler and throw it where it mustn't be thrown. This compiles and runs in Java 6 and 7, throwing a <code>SQLException</code> without <code>throws</code> or <code>catch</code> clause:</p> <pre><code>public class Test { // No throws clause here public static void main(String[] args) { doThrow(new SQLException()); } static void doThrow(Exception e) { Test.&lt;RuntimeException&gt; doThrow0(e); } static &lt;E extends Exception&gt; void doThrow0(Exception e) throws E { throw (E) e; } } </code></pre> <p>The generated bytecode indicates that the JVM doesn't really care about checked / unchecked exceptions:</p> <pre><code>// Method descriptor #22 (Ljava/lang/Exception;)V // Stack: 1, Locals: 1 static void doThrow(java.lang.Exception e); 0 aload_0 [e] 1 invokestatic Test.doThrow0(java.lang.Exception) : void [25] 4 return Line numbers: [pc: 0, line: 11] [pc: 4, line: 12] Local variable table: [pc: 0, pc: 5] local: e index: 0 type: java.lang.Exception // Method descriptor #22 (Ljava/lang/Exception;)V // Signature: &lt;E:Ljava/lang/Exception;&gt;(Ljava/lang/Exception;)V^TE; // Stack: 1, Locals: 1 static void doThrow0(java.lang.Exception e) throws java.lang.Exception; 0 aload_0 [e] 1 athrow Line numbers: [pc: 0, line: 16] Local variable table: [pc: 0, pc: 2] local: e index: 0 type: java.lang.Exception </code></pre> <p>The JVM accepting this is one thing. But I have some doubts whether <em>Java-the-language</em> should. Which parts of the JLS justify this behaviour? Is it a bug? Or a well-hidden "feature" of the Java language?</p> <p>My feelings are:</p> <ul> <li><code>doThrow0()</code>'s <code>&lt;E&gt;</code> is bound to <code>RuntimeException</code> in <code>doThrow()</code>. Hence, no <code>throws</code> clause along the lines of <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html#jls-11.2">JLS §11.2</a> is needed in <code>doThrow()</code>.</li> <li><code>RuntimeException</code> is assignment-compatible with <code>Exception</code>, hence no cast (which would result in a <code>ClassCastException</code>) is generated by the compiler.</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload