【问题标题】:Catch exception while initializing static final variable初始化静态最终变量时捕获异常
【发布时间】:2013-07-26 06:12:57
【问题描述】:

我有以下代码:

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。

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

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

整个想法是

  • 初始化应用程序配置参数。
  • 如果初始化成功,继续。
  • 如果没有,请提醒用户并终止应用程序。

【问题讨论】:

    标签: java exception-handling static final


    【解决方案1】:

    你可以这样捕捉它:

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

    【讨论】:

    • 最后一个赋值property_file_location = myTempValue;必须在finally块内
    【解决方案2】:

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

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

    【讨论】:

    • 以上参数是实际参数的子集。我有我一直在使用的参数。这种方法应该对我有用。 PropertyUtils.getProperty(),会给我做异常处理的方法。我会试试的。
    【解决方案3】:

    您可能想使用静态块:

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

    【讨论】:

    • 那是因为如果它失败了,你的最终变量就没有设置。所以你可以添加一个finally {proeprty_file_location = null};
    • 即使有 finally 子句,也可以尝试编译它。
    猜你喜欢
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多