java - 为什么编译取决于实例初始化程序中抛出异常的方式?

标签 java initializer

为什么第一个代码片段无法编译(编译错误“初始化程序未正常完成”),而第二个代码片段编译正常?唯一的区别在于抛出异常的方式!

class CompilationFailsClass {   

   {
      // c.ERR Initializer does not complete normally
      throw new IOException();   
   }

   public CompilationFailsClass() throws IOException {
        // constructor
   }
}

对比

class CompilationOKClass {

   // with empty body effect is exactly same
   static void f() throws IOException { throw new IOException(); }

   {
      f(); // OK !
   }

   public CompilationOKClass() throws IOException {
   }
}

JLS §11.2.3 :

It is a compile-time error if an instance variable initializer (§8.3.2) or instance initializer (§8.6) of a named class can throw a checked exception class, unless the named class has at least one explicitly declared constructor and the exception class or one of its superclasses is explicitly declared in the throws clause of each constructor.

最佳答案

JLS 在 section 8.6 中对此非常清楚。 :

It is a compile-time error if an instance initializer cannot complete normally (§14.21).

在第一个示例中,实例初始化程序无法正常完成。

在第二个示例中,就编译器而言它可以正常完成。它永远不会,但编译器不知道这一点,因此没关系。

关于java - 为什么编译取决于实例初始化程序中抛出异常的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645448/

相关文章:

python - 初始化器与构造器

c - 当你声明一个指针时,它是 NULL 吗?

java - 将 MySql 日期映射到 java 对象

java - PriorityQueue 经常需要调整比较器 - 我该如何最好地处理这个问题?

java - 在 JFrame 中显示 Excel 工作表

c++ - 有没有办法在 for 循环初始值设定项中定义两种不同类型的变量?

c - 为什么这段代码输出初始化器中的第一个元素?

swift - Swift 枚举中的默认初始化被忽略

java - 如何避免将已删除的实例传递到与 Set 的一对多关系上的合并?

启动时 Java GUI 应用程序框架无法正确显示?