繁体   English   中英

在初始化静态最终变量时捕获异常

[英]Catch exception while initializing static final variable

我有以下代码:

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

它从“ VM参数”中读取并分配给变量。

由于静态最终变量仅在类加载时初始化,因此如果有人忘记传递参数,如何捕获异常。

截至目前,当我使用'property_file_location'变量时,在以下情况下会遇到异常:

  • 如果存在值,并且位置错误,则会出现FileNotFound异常。
  • 如果未正确初始化(值为null),则抛出NullPointerException。

我只需要在初始化时处理第二种情况。

类似的是第二变量的情况。

整个想法是

  • 初始化应用程序配置参数。
  • 如果成功初始化,请继续。
  • 如果不是,请警告用户并终止应用程序。

您可以通过以下方式捕获它:

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

您可以按照其余答案的建议使用静态初始化程序块。 甚至最好将此功能移至静态实用程序类,以便您仍然可以将它们用作单行代码。 您甚至可以提供默认值,例如

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

但是,如果不希望这些属性始终存在,则建议不要将它们初始化为静态变量,而应在正常执行期间读取它们。

// 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
}

您可能要使用静态块:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM