我從不會拋出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…