我从不会抛出NullPointerException。对我来说,它是一个出现在代码中当出现问题时,需要开发人员看看会发生什么。然后(s)他固定的原因,它不会再次发生。
我使用IllegalStateException表示对象配置不正确或调用的顺序不正确。但是,我们都知道,理想情况下,一个对象应该确保它不能处于坏的状态,你不能以错误的顺序调用它(使一个构建器和一个结果对象…)。
当一个方法检测到其参数不正确时,我使用了很多IllegalArgumentException。这是任何公共方法的责任,停止处理(以避免更难以理解的间接错误)。另外,在方法开始的几个ifs提供文档目的(文档从不偏离代码,因为它是代码:-))。
public void myMethod(String message, Long id) {
if (message == null) {
throw new IllegalArgumentException("myMethod's message can't be null");
// The message doesn't log the argument because we know its value, it is null.
}
if (id == null) {
throw new IllegalArgumentException("myMethod's id can't be null");
// This case is separated from the previous one for two reasons :
// 1. to output a precise message
// 2. to document clearly in the code the requirements
}
if (message.length()<12) {
throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
// here, we need to output the message itself,
// because it is a useful debug information.
}
}
我还使用特定的运行时异常来表示更高级别的异常条件。
For example, if a module of my application couldn’t start, I might have a ModuleNotOperationalException thrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules…