簡體   English   中英

Java - 當沒有屬性時,代碼總是會拋出 Null 指針異常?

[英]Java - code will always throw a Null Pointer Exception when no Property is present?

我繼承了以下 java 代碼,它從properties file中獲取property值:

    String personName = this.properties.getFilePropertty("person.name");
    if (personName != null) {
       // do something else
    } else {
        // do something
    }

上述流程中的預期行為是personName將從屬性文件中檢索,或者如果不存在則返回為null ,並進行相應處理。

但是,當該屬性不存在時, getFileProperty()方法中會拋出異常(如下所示)。

我怎樣才能解決這個問題以獲得預期的行為?

獲取文件屬性():

            public String getFileProperty(String name) throws SystemPropertiesException {
            
            return Optional.ofNullable( this.properties.getProperty(name, null) )
            .orElseThrow(()->new PropertiesException("Can not get property!"));
            
             }

注意 - 上面代碼中調用的getProperty()方法是java utils getProperty方法。

您可以使用嘗試捕獲

try{
    String personName = this.properties.getFilePropertty("person.name");
    //if it's not null there will be no exception so you can directly use the personName 
    
}catch(SystemPropertiesException ex){
    //else there is an exception to handle here 
}

您應該將代碼包裝在 try catch 塊中。

try {
    String personName = this.properties.getFileProperty("person.name");
    // do something else
} catch (PropertiesException exception) {
    // do something
}

編輯:或者為.getFileProperty()提供一個 defaultValue

String personName = this.properties.getFilePropertty("person.name", "NO_VALUE_FOUND");
if (!personName.equals("NO_VALUE_FOUND")) {
    // do something else
} else {
    // do something
}

您應該使用try catch而不是if else condition 拋出 SystemPropertiesException 時,如果未找到 person.name,請執行您的邏輯。

 try { String personName = this.properties.getFileProperty("person.name"); //do something assuming the person.name has been retrieved. } catch(SystemPropertiesException e) { //do something if the person.name was not found }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM