我的方法被定义为...
public static void myMethod 抛出 IOException ....
如何使用 Logger 类来记录抛出到名为“test.log”的文件的异常。我听说过使用 logger.throwing...但它似乎不起作用。谁能给我一步步提示如何做到这一点?我基本上只需要记录抛出的异常(我没有使用 try catch)。非常感谢!
最佳答案
您需要添加一个 catch 子句。下面是使用 java.util.logging.Logger 的开始。请注意,许多项目使用 Apache 记录器,它功能更强大,也更复杂。假设您有一个类 com.myCompany.Foo 可以读取一些文件内容
通常,在类的开头,在静态字段声明中,您将拥有
private static final Logger LOGGER = Logger.getLogger("com.myCompany.Foo");
然后,当你有一个抛出异常的方法时(这是一个愚蠢的方法!)
int readFirstCharOfFile(File f) throws IOException {
FileReader reader = null;
try {
reader = new FileReader(f);
return reader.read();
}
catch (IOException ioe) {
// You have a lot of possibilities here, but this seems most reasonable
LOGGER.log(Level.SEVERE, ioe.getMessage(), ioe);
// whether you rethrow the Exception "depends" on the contract, but, in our case
// the method declaration says that we do, so we do.
throw ioe;
}
finally {
if (reader != null)
reader.close();
}
}
更困难的部分是配置记录器以在您想要的位置写入。 IIRC,默认情况下它会进入标准错误。那里有很多我从未完全理解的“魔法”,所以我无法解释所有错综复杂的事情。
关于java - 抛出异常的记录方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8899118/