Java 是否有任何语法来管理声明和初始化类的成员变量时可能引发的异常?
public class MyClass
{
// Doesn't compile because constructor can throw IOException
private static MyFileWriter x = new MyFileWriter("foo.txt");
...
}
或者这样的初始化是否总是必须移动到我们可以声明的方法中throws IOException
或者将初始化包装在 try-catch 块中?
使用静态初始化块
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
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)