2
我有一个构造函数,它在同一个类中调用另一个构造函数。问题是我想捕获异常并将它们向前抛出到调用第一个构造函数的方法。但是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();
}
}
如果有人能解释我该如何做到这一点很好。奖金是知道为什么语言必须这样做,因为这总是很有趣。
为什么你抓住例外呢?如果你不抓住他们,他们只会回到所谓的第一个构造者身上。 –
请参阅http://stackoverflow.com/a/1168356/1729686为什么需要先调用this()和super()。 – Liam