我有一个构造函数,它调用同一个类中的另一个构造函数。问题是我想捕获异常并将它们向前抛出到调用第一个构造函数的方法。然而 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();
}
}
如果有人可以解释我如何做到这一点,那就太好了。一个好处是知道为什么语言必须以这种方式表现,因为这总是很有趣。