我正在阅读J. Bloch的有效Java,现在我在关于记录未经检查的异常的部分。他说,记录未检查的异常
使用Javadoc @throws标记来记录每个未检查的异常 ,方法可以抛出[...]。
public interface Parameters {
//other method ommited
/**
* __DESCRIPTION_OMMITED__
*
* @throws ParameterAlreadyExistsException If a parameter with the same name already exists in this container.
*/
public <M> void put(ParameterMetaData<M> p, M value);
}
其中public interface ParameterMetaData<ValueType>{ }
只是一个标记,以保证编译时类型安全。 ParameterAlreadyExistsException
是RuntimeException
的直接子类。
这里是它的一个基地implemetation:
public final class ParametersImpl implements Parameters{
private final Map<ParameterMetaData<?>, Object> parameters;
@Override
public <M> void put(ParameterMetaData<M> p, M value){
if(value == null)
return;
if(parameters.containsKey(p))
throw new ParamAlreadyExistsException(String.format("The parameter with the name %s already exists. Value: %s", p.getClass(), parameters.get(p)));
try{
parameters.put(p, value);
} catch (Exception e){
throw new RuntimeException(String.format("Parameter insertion failed. ParameterMetaData: %s Value: %s", p.getName(), value), e);
// ^----------------Here non-documented exception is thrown.
}
}
//remainders ommited
}
由于Map#put(K, V)方法抛出我的implementaiton使用它,并抛出RuntimeException
如果服用点出了问题,我应该如何对此进行记录?我应该这样做吗?目前很难说接口文档为什么会引发RuntimeException。
问题:我应该如何处理执行特定的异常?我应该记录它们吗?
Map.put()不会抛出任何检查的异常。它引发的所有运行时异常都是代码中的错误信号。你没有发现任何一个。 –
相关:http://stackoverflow.com/questions/824217/should-methods-that-throw-runtimeexception-indicate-it-in-method-signature?rq=1 – 2015-11-06 06:44:33
@JBNizet其实它没有。但是如果我没有捕获它,它会传播,接口的客户端会看到一些关于放入内部HashMap的混淆信息。也许它会很好地抓住它并转化为更合适的例外? –