title: Java SneakyThrow of exceptions, type erasure
body: <p>Can someone explain this code?</p>
  
  <pre><code>public class SneakyThrow {
  
  
    public static void sneakyThrow(Throwable ex) {
      SneakyThrow.&lt;RuntimeException&gt;sneakyThrowInner(ex);
    }
  
    private static &lt;T extends Throwable&gt; T sneakyThrowInner(Throwable ex) throws T {
      throw (T) ex;
    }
  
  
  
    public static void main(String[] args) {
      SneakyThrow.sneakyThrow(new Exception());
    }
  
  
  }
  </code></pre>
  
  <p>It may seems strange, but this doesn't produce a cast exception, and permits to throw a checked exception without having to declare it in the signature, or to wrap it in an unchecked exception.</p>
  
  <p>Notice that neither <code>sneakyThrow(...)</code> or the main are declaring any checked exception, but the output is:</p>
  
  <pre><code>Exception in thread "main" java.lang.Exception
      at com.xxx.SneakyThrow.main(SneakyThrow.java:20)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:601)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
  </code></pre>
  
  <p>This hack is used in Lombok, with the annotation @SneakyThrow, which permits to throw checked exceptions without declaring them.</p>
  
  <hr>
  
  <p>I know it has something to do with type erasure, but i'm not sure to understand every part of the hack. </p>
  
  <hr>
  
  <p><strong>Edit:</strong>
  I know that we can insert an <code>Integer</code> in a <code>List&lt;String&gt;</code> and that checked/unchecked exceptions distinction is a compile time feature.</p>
  
  <p>When casting from a non-generic type like <code>List</code> to a generic type like <code>List&lt;XXX&gt;</code> the compiler produces a warning. But it's less common to cast to a generic type directly like <code>(T) ex</code> in the above code.</p>
  
  <p>If you want, the part that seems strange for me is that I understand that inside the JVM a <code>List&lt;Dog&gt;</code> and <code>List&lt;Cat&gt;</code> looks the same, but the above code seems to mean that finally we can also assign a value of type Cat to a variable of type Dog or something like that.</p>