This snippet throws an NullPointerException due to the fact that its unboxed to a primitive type and Long.longValue() is called, right?
Tha
It is a good idea to write a small private helper for cases like this. Those can handle producing correct casts, error messages and default values.
It is good to put enough "state" of the operation into the exception (in this case the option name and the value - maybe even a string representation of the options map if not found).
Something like:
private long safeGetLong(Map options, String name) {
if (name == null || options == null)
throw new IllegalArgumentExcption("You need to give options and name. (name="+name+", opts=" + options));
Object val = options.get(name);
if (val == null)
throw new ConfigurationException("The option name="+name+" is unknown");
if (val instanceof Long)
return val.longValue();
String strVal = null;
try
{
strVal = val.toString();
return Long.parseValue(strVal);
} catch (Exception ex) {
throw new ConfigurationException("Cannot parse " + name + "=" + strVal + " into a Long.");
}
}
Of course having a configuration object which allows typed access is even better.
There are some validation frameworks which could do that for you, but I typically end up writing the code myself as it better fits into IN8L and exception hieracies or logging conventions of the application in question. It is hard to make that generic.