为什么Exception会被当成RuntimeException抛出?

为什么Exception会被当成RuntimeException抛出?,第1张

为什么Exception会被当成RuntimeException抛出?

为什么以下代码可以通过编译不报错?btw,运行时还是会报原有的Exception,不会吞掉

public class ThrowAsUnchecked {
  public static void main(String[] args) {
//    throwAsUnchecked(new Exception("Testing new checked exception"));
    throwAsUnchecked(new IOException());
//    throwAsUnchecked(new RuntimeException("Testing new checked exception"));
  }

  @SuppressWarnings("unchecked")
  private static  void throwAsUnchecked(Exception exception) throws E {
    throw (E) exception;
  }
}

可参考的链接:stackoverflow How Java become unchecked exception [duplicate],
以及stackoverflow A peculiar feature of exception type inference in Java 8中的sneakyThrow

目前来看,应与泛型的type inference有关,有空再来研究

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5609066.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存