2013-09-22 57 views
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(); 
    } 
} 

如果有人能解释我该如何做到这一点很好。奖金是知道为什么语言必须这样做,因为这总是很有趣。

+3

为什么你抓住例外呢?如果你不抓住他们,他们只会回到所谓的第一个构造者身上。 –

+0

请参阅http://stackoverflow.com/a/1168356/1729686为什么需要先调用this()和super()。 – Liam

回答

3

在构造函数中你不需要那些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 
    } 
} 

说了这么多,这是很少一个好主意,从构造函数抛出一个checked异常,更糟糕的处理它们在调用者的代码。
如果引发异常,并在调用方法中处理它。然后你简单地忽略了你的实例没有完全初始化的事实。进一步处理该实例将导致一些意外行为。所以,你应该避免它。