log4j异常处理问题
我有一个初始化 log4j 的类。这段代码永远不会打印或退出,我不明白为什么。
public class MyLog
{
private static Logger log;
static
{
log = Logger.getRootLogger();
try
{
PropertyConfigurator.configure("somefileNameWhichDoesNotExist");
}
catch(Exception t)
{
System.out.println("oops logging cant be set, lets exit");
System.exit(0);
}
I have a class which initializes my log4j. This code will never print or exit, I dont understand why.
public class MyLog
{
private static Logger log;
static
{
log = Logger.getRootLogger();
try
{
PropertyConfigurator.configure("somefileNameWhichDoesNotExist");
}
catch(Exception t)
{
System.out.println("oops logging cant be set, lets exit");
System.exit(0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么假设文件不存在时会抛出异常?我刚刚快速浏览了 API 文档,他们没有提及任何有关丢失文件的处理 - 因此该条件很可能会被忽略。
编辑:只需阅读您的附加评论,所以情况并非如此。
确保静态块实际上正在执行。
编辑:PropertyConfigurator 正在捕获异常,并在内部处理它。这就是为什么你看不到异常。 请参阅源代码 - 第 370-380 行。
Why do you assume that an exception will be thrown when the file doesn't exist? I just had a quick look at the API docs, and they don't say anything about the handling of missing files - so it's just as likely that the condition would just be ignored.
EDIT: just read your additional comments, so that's not the case.
Make sure that the static block is actually executing.
EDIT: PropertyConfigurator is catching the exception, and handling it internally. That's why you don't see the exception. See the source - lines 370-380.
PropertyConfigurator#configure (String configFilename) 不会抛出任何已检查的 Exception,因此
catch(Exception t)
永远不会捕获任何内容。检查 ApiDoc,因为当你想捕获异常时,在 throws 子句中必须有一个声明的异常。PropertyConfigurator#configure(String configFilename) does not throw any checked Exception, therefore there is never anything to catch with
catch(Exception t)
. Check the ApiDoc, because there has to be a declared Exception in the throws-clause, when you want to catch Exception.你能告诉我,找到问题的答案了吗?
这对我来说非常有用。
我的解决方案是:
也许你有更好的解决方案?
多谢!
Could you tell me, have found the answer to the question?
It will be very useful for me.
My solution is:
May be you have a better one?
Thanks a lot!
难道是configure方法抛出了Error?
更改代码以捕获 java.lang.Throwable (http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html) 而不是 Exception。
Could it be that the configure method is throwing an Error?
Change your code to catch a java.lang.Throwable (http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html) instead of Exception.