Krolique
Krolique

Reputation: 682

log4j exception handling problem

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

Upvotes: 2

Views: 3199

Answers (4)

Elena
Elena

Reputation: 549

Could you tell me, have found the answer to the question? It will be very useful for me.

My solution is:

try
{
    Properties props = new Properties();
    props.load(new FileInputStream(propFilePath));
    PropertyConfigurator.configure(props);
}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}
catch (IOException e)
{
    e.printStackTrace();
}

May be you have a better one? Thanks a lot!

Upvotes: 1

Michael Konietzka
Michael Konietzka

Reputation: 5499

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.

Upvotes: 1

Mike Baranczak
Mike Baranczak

Reputation: 8374

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.

Upvotes: 3

iruediger
iruediger

Reputation: 953

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.

Upvotes: 0

Related Questions