我有一个构造函数,它在同一类中调用另一个构造函数。问题是我想捕获异常并将它们向前扔给调用第一个构造函数的方法。但是Java不允许这样做,因为构造函数调用必须是构造函数中的第一条语句。
public Config(String fn) throws IOException, ExcFormattingError {
theFile = fn;
try { cfRead(); }
catch(FileNotFoundException e) {
//create a new config with defaults.
theConfig = defaultConfig();
create();
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
fixMissing(theConfig);
}
public Config() throws IOException, ExcFormattingError {
try {
//Line below is in error...
this("accountmgr.cfg");
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
}
如果有人可以解释我该怎么做,那将很好。一个额外的好处就是知道为什么这种语言必须如此行事,因为这总是很有趣。
您不需要try-catch
构造函数中的那些块(事实上,您已经知道了,您不能在其中编写块)。因此,将您的构造函数更改为:
public Config() throws IOException, ExcFormattingError {
this("accountmgr.cfg");
}
实际上catch
,您的构造函数中的代码块几乎无济于事。它只是重新创建相同异常的实例,然后将其抛出。考虑到如果引发了异常,它将自动传播到可以处理该异常的调用者代码这一事实,因此实际上并不需要这样做。
public void someMethod() {
Config config = null;
try {
config = new Config();
} catch (IOException e) {
// handle it
} catch (ExcFormattingError e) {
// handle it
}
}
话虽这么说,从构造函数中抛出一个检查的异常几乎不是一个好主意,更糟糕的是在调用者代码中处理它们。
如果引发了异常,则可以在调用方法中对其进行处理。然后,您只是忽略了实例尚未完全初始化的事实。继续执行该实例将导致某些意外行为。因此,您应该避免使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句