Static final variable initialization exception exception

I have the 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 "VM arguments" and assigns to variables.

Since a static final variable is only initialized when the class is loaded, how can I catch an exception if someone forgets to pass a parameter.

At the moment, when I use the variable 'property_file_location', an exception occurs in the following cases:

  • If a value is present and the location is erroneous, a FileNotFound exception is thrown.
  • If it is not initialized correctly (null), it throws a NullPointerException.

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

Sidimen is the case of the second variable.

Whole idea

  • To initialize application configuration settings.
  • If successfully initialized, continue.
  • If not, warn the user and stop using.
+4
source share
3 answers

You can use a static initializer block as suggested by the rest of the answers. It’s even better to move this functionality to a static utility class so that you can still use them as single-line. You could even provide default values, for example.

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

However, if these properties do not exist all the time, I would suggest not to initialize them as static variables, but to 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 } 
+2
source

You can catch it like this:

 public class LoadProperty { public static final String property_file_location; static { String myTempValue = MY_DEFAULT_VALUE; try { myTempValue = System.getProperty("app.vmargs.propertyfile"); } catch(Exception e) { myTempValue = MY_DEFAULT_VALUE; } property_file_location = myTempValue; } } 
+4
source

You can use a static block:

 public static final property_file_location; static { try { property_file_location = System.getProperty("app.vmargs.propertyfile"); } catch (xxx){//...} } 
0
source

Source: https://habr.com/ru/post/1493585/


All Articles