本文介绍了字段初始化中未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class MyClass
{
//不能编译,因为构造函数可以抛出IOException
private static MyFileWriter x = new MyFileWriter(foo.txt);
...
}
或者做这些初始化总是必须移动转换成一个方法,我们可以声明 throws IOException
或将初始化包装在try-catch块中。
解决方案
使用静态初始化块
public class MyClass
{
private静态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
...
}
Does Java have any syntax for managing exceptions that might be thrown when declaring and initializing a class's member variable?
public class MyClass
{
// Doesn't compile because constructor can throw IOException
private static MyFileWriter x = new MyFileWriter("foo.txt");
...
}
Or do such initializations always have to be moved into a method where we can declare throws IOException
or wrap the initialization in a try-catch block?
解决方案
Use a static initialization block
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
...
}
这篇关于字段初始化中未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!