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)
| 归档时间: |
|
| 查看次数: |
6674 次 |
| 最近记录: |