我应该将 getSharedPreferences 包装在 try catch 中吗?

Should I wrap getSharedPreferences inside try catch?

我使用此功能从 Android 应用中提取共享首选项。但是,我不确定请求的字段是否存在。当字段不存在时,我应该将代码包装在 try catch 中还是 getString() 是安全的?

public String loadPreferences(String what){
    SharedPreferences settings  =this.getSharedPreferences("settings", Context.MODE_PRIVATE);
    String content =settings.getString(what, "empty");
    return content;
}

如果 "field",你的意思是任何 what 键入的值,getString() 将不会 return null 在你的代码片段中。它将 return 由 what 键入的值,或者 "empty" 如果该首选项没有值。

你应该read documentation of getString here,它清楚地说,

Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a String. This value may be null.

在你的例子中,defValue"empty"

因此只有当您尝试 return 的值不是指定类型时才有可能发生异常,尽管

永远不会出现 getString() 的情况

如果你通过这个 link 搜索:https://developer.android.com/reference/android/content/SharedPreferences.html

你会发现这个方法:

getString(String key, String defValue)

这意味着,如果您没有使用此键在 SharedPreferences 中存储任何内容,并且您正在尝试获取此键的值,那么它将 return 默认值

所以在你的情况下

String content =settings.getString(what, "empty");

对于 what 键,如果你没有用这个键存储任何东西,如果你想获取它的值,那么它将 return 默认值,在你的情况下是 "empty"