views:

55

answers:

3

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);
      }
A: 

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.

iruediger
I did both actually, Catch(Throwable t){} followed by catch(Exception e) {} AND NEITHER of them got executed.
Krolique
+2  A: 

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.

Mike Baranczak
java will throw an exception somewhere deep deep down for sure. i know this. because no matter what they will use they will use java.lang and that will say NO FILE! exception and log4j prints a stack trace which has the exception. the only problem is I can't handle this myself and say kill the thread or something.
Krolique
i checked the static block is executed.
Krolique
So you're saying that a stack trace is printed, but the exception is never thrown to your code? This would mean that Log4J is catching the exception inside its own code.
Mike Baranczak
Mike, yea Thread.currentThread().interrupt();. I guess I'm going to have code around this in my main thread. TY!
Krolique
+1  A: 

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.

Michael Konietzka
Yes that was the first thing I've checked. No exception was thrown, but yet stdout printed an exception. Naturally I wanted to capture it, right?
Krolique
I guess the exception was printed to `System.err`, not to `System.out`. Nevertheless you can never catch a `java.lang.Exception` if it is not declared in the throws-clause. (despite of bytecode-manipulations)
Michael Konietzka