字段初始化中未处理的异常

kpo*_*zin 27 java initialization exception

Java是否有任何语法来管理在声明和初始化类的成员变量时可能抛出的异常?

public class MyClass
{
  // Doesn't compile because constructor can throw IOException
  private static MyFileWriter x = new MyFileWriter("foo.txt"); 
  ...
}
Run Code Online (Sandbox Code Playgroud)

或者这些初始化总是必须移动到一个方法,我们可以throws IOException在try-catch块中声明或包装初始化?

Mat*_*ttC 20

使用静态初始化块

public class MyClass
{
  private static MyFileWriter x;

  static {
    try {
      x = new MyFileWriter("foo.txt"); 
    } catch (Exception e) {
      logging_and _stuff_you_might_want_to_terminate_the_app_here_blah();
    } // end try-catch
  } // end static init block
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 如果要在执行处理后传播,还可以选择抛出RuntimeException. (2认同)
  • 如果必须初始化MyFileWriter以使类正常运行,则应抛出RuntimeException,这将阻止加载类.这将有效地呈现任何试图使用此类的代码注定要失败,如果它对于应用程序的运行至关重要,这可能是期望的行为.不执行此操作而进行日志记录可能会使对MyClass方法的每次调用都失败. (2认同)