Mentre scrivevo il codice per un'altra risposta su questo sito mi sono imbattuto in questa particolarità:
static void testSneaky() {
final Exception e = new Exception();
sneakyThrow(e); //no problems here
nonSneakyThrow(e); //ERRROR: Unhandled exception: java.lang.Exception
}
@SuppressWarnings("unchecked")
static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
throw (T) t;
}
static <T extends Throwable> void nonSneakyThrow(T t) throws T {
throw t;
}
Innanzitutto, sono abbastanza confuso sul motivo per cui la sneakyThrowchiamata è OK per il compilatore. Per quale possibile tipo ha dedotto Tquando non viene menzionato da nessuna parte un tipo di eccezione non controllato?
Secondo, ammettendo che funzioni, perché il compilatore si lamenta della nonSneakyThrowchiamata? Sembrano molto simili.
sneakyThrowchiamata. Le norme speciali sull'inferenza dellethrows Tforme non esistevano nelle specifiche di Java 7.