Search code examples
javaresourcebundle

ResourceBundle.getString with fallback if key not found


I am trying to find a way to use resource bundle with possibility of some kind of a fallback if the key is not found. Currently the only way I have found is catching the exception:

try {
    resourceBundle.getString(key);
} catch (MissingResourceException ex) {
    return defaultValue;
}

Is there a nicer solution to this problem (something like getOrDefault in Map)? Maybe another library with nicer API?


Solution

  • Not every data structure supports such a method. In your case, you'd normally check whether the key is contained or not by using the containsKey method.

    Catching an exception as "normal" flow in the code is not what I'd call a decent architecture.