A peculiar feature of exception type inference in Java 8

前端 未结 3 425
太阳男子
太阳男子 2020-11-29 19:00

While writing code for another answer on this site I came across this peculiarity:

static void testSneaky() {
  final Exception e = new Exception();
  sneaky         


        
3条回答
  •  温柔的废话
    2020-11-29 19:19

    With sneakyThrow, the type T is a bounded generic type variable without a specific type (because there is no where the type could come from).

    With nonSneakyThrow, the type T is the same type as the argument, thus in your example, the T of nonSneakyThrow(e); is Exception. As testSneaky() does not declare a thrown Exception, an error is shown.

    Note that this is a known interference of Generics with checked exceptions.

提交回复
热议问题