Search code examples
javaexceptionstaticfinal

Catch exception while initializing static final variable


I have following code:

public class LoadProperty
{
public static final String property_file_location = System.getProperty("app.vmargs.propertyfile");
public static final String application-startup_mode = System.getProperty("app.vmargs.startupmode");
}

It reads from 'VM arguments' and assigns to variables.

Since static final variable is only initialized at class load, how can I catch exception in case some one forgets to pass parameter.

As of now, when I am using 'property_file_location' variable, exception is encountered in following cases:

  • If value is present, and location is wrong, FileNotFound exception comes.
  • If it is not initialized properly(value is null), it throws NullPointerException.

I need to handle second case at time of initialization only.

Similiar is case of second variable.

Whole idea is

  • To initialize application configuration parameters.
  • If successfully initialized, continue.
  • If not, alert user and terminate application.

Solution

  • You can use a static initializer block as suggested by the rest of the answers. Even better move this functionality to a static utility class so you can still use them as an one-liner. You could then even provide default values e.g.

    // PropertyUtils is a new class that you implement
    // DEFAULT_FILE_LOCATION could e.g. out.log in current folder
    public static final String property_file_location = PropertyUtils.getProperty("app.vmargs.propertyfile", DEFAULT_FILE_LOCATION); 
    

    However if those properties are not expected to exist all the time, I would suggest to not initialize them as static variables but read them during normal execution.

    // in the place where you will first need the file location
    String fileLocation = PropertyUtils.getProperty("app.vmargs.propertyfile");
    if (fileLocation == null) {
        // handle the error here
    }