I’m using the following code for checking if a key exists in a Map instance:
if (!map_instance.containsKey(key))
throw new RuntimeException("Specified key doesn't exist in map");
else
return map_instance.get(key);
My question is:
Is there a utility or Map implementation to simplify the above code, such as:
custom_map.get(key,"Specified key doesn't exist in map");
My goal is: if key does not exist in map, the map implementation throws an exception with the passed string.
I don’t know whether or not my desire is reasonable?
(Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)
You could take a look into the configuration map from Apache commons. It doesn’t implements
Map, but has a similar interface with a few Helper methods, likegetString,getStringArray,getShortand so on.With this implementation you could use the method
setThrowExceptionOnMissing(boolean throwExceptionOnMissing)and could catch it and handle as you want.Isn’t exactly with a configurable message but from my point of view it doesn’t make sense to throw a fixed exception just with a custom message since the exception type itself depends on the context where the
getmethod is invoked. For example, if you perform a get of an user the exception would be something related to that, maybeUserNotFoundException, and not just aRuntimeExceptionwith the message: User not Found in Map!