0

Could someone explain why the first cast does not give a CCE ?

public class Test {

  public static void main(String[] args) throws Throwable {
    Test.<RuntimeException>throwIt(new Exception());
  }

  @SuppressWarnings("unchecked")
  private static <T extends Throwable> void throwIt(Throwable throwable) throws T {
    throw (T) throwable; // no ClassCastException
    throw (RuntimeException) throwable; // ClassCastException(as it should be)
  }
}

P.S. Comment one cast (otherwise it won't compile).

Bax
  • 4,260
  • 5
  • 43
  • 65

1 Answers1

1

This is the feature of Java generics realization, it was realized through type erasure, that's why (T) cast actually cast it to Throwable as leftmost bound. Because, new Exception() produces a Throwable object you can safely throw it.

You can check it in JSL http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#108979

Gunnarr
  • 101
  • 5