我繼承了以下 java 代碼,它property從 a獲取 a 的值properties file:
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方法。
uj5u.com熱心網友回復:
您可以使用 try catch
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
}
uj5u.com熱心網友回復:
您應該將代碼包裝在 try catch 塊中。
try {
String personName = this.properties.getFileProperty("person.name");
// do something else
} catch (PropertiesException exception) {
// do something
}
編輯:或者提供一個默認值 .getFileProperty()
String personName = this.properties.getFilePropertty("person.name", "NO_VALUE_FOUND");
if (!personName.equals("NO_VALUE_FOUND")) {
// do something else
} else {
// do something
}
uj5u.com熱心網友回復:
您應該使用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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/399171.html
下一篇:從地圖流中重用lambda
