java记录未检查的异常
我正在阅读J.Bloch的《高效Java》,现在我在读关于记录未经检查的异常的部分。他说
Use the Javadoc @throws tag to document each unchecked exception that a method can throw [...].
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
的一个直接子类
以下是它的基本实现:
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)方法抛出,而我的实现使用它并抛出RuntimeException
如果出现问题,我应该如何记录这一事实?我应该这样做吗?目前,从接口文档判断引发RuntimeException的原因可能很难说
问题:我应该如何处理特定于实现的异常?我应该把它们记录下来吗
# 1 楼答案
你没有。正如JB Nizet在评论中指出的,这是一个bug,你应该测试/修复这些问题
如果您担心会向用户显示内部错误,可以显示一般错误,比如“发生未知错误”。在日志记录中,您可以记录实际的异常,这样您的用户就可以向您报告错误,您就可以看到出了什么问题