簡體   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