我正在使用 PMD 规则列表对代码库进行投诉。其中包括不允许抛出或捕获 NullPointerException
。我发现此方法需要 2 个实例变量为非空才能运行。它抛出一个 NullPointerException
否则:
public String build() {
if (apiKey == null || url == null) {
throw new NullPointerException(
"Cannot build: API key and URL must be set");
}
它应该抛出什么?在我看来,NullPointerException
将是 bast 调用。唯一想到的是 IllegalArgumentException
,但这些并不是真正的参数,所以我认为它不适合。
最佳答案
IllegalStateException
在这里似乎完全合适:
Signals that a method has been invoked at an illegal or inappropriate time.
这相当清楚地描述了情况,不是吗?
关于java - 实例变量为 null 时抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22483089/