使用DOMConfigurator时无法捕获FileNotFoundException

时间:2010-10-19 10:14:05

标签: java exception

我有以下代码:

try {  
    DOMConfigurator.configure(url+log4j.xml);
} catch(Exception e) {   
    e.printStackTrace();   
}

如果log4j.xml不存在,我希望FileNotFoundException,然后执行catch-block。

但是当文件不存在时我没有看到异常,为什么会这样?

3 个答案:

答案 0 :(得分:2)

如果你看the source of DOMConfigurator.doConfigure它看起来像是捕获Exception然后只记录错误而不是重新抛出它。因此,FileNotFoundException不会将其恢复为您的主叫代码。

try {
...
} catch (Exception e) {
    if (e instanceof InterruptedException || e instanceof InterruptedIOException) {
        Thread.currentThread().interrupt();
    }
    // I know this is miserable...
    LogLog.error("Could not parse "+ action.toString() + ".", e);
} 

要解决此问题,您可以预先检查文件是否存在。

答案 1 :(得分:0)

尝试捕获Throwable而不是Exception并执行打印堆栈跟踪。这样您就可以捕获任何错误或异常,并相应地更改您的代码。

答案 2 :(得分:0)

如果要从log4j禁用这些消息,可以在安静模式下设置log4j:

LogLog.setQuietMode(true);
相关问题