在《Effective Java, 2nd edition》一书的Item 2中,有一段代码,作者想在其中禁止一个对象的空初始化。
class Example {
private Example() {
throw new AssertionError();
}
}
抛出的异常类型,让我很困惑。
我不明白抛出 AssertionError
是因为缺少更合适的错误还是应该是这种方式。
据我了解,当 assert
语句失败时,框架会引发此错误。另外,在javadoc中它只是写了
[An AssertionError is] Thrown to indicate that an assertion has failed.
但我没有看到这里违反了任何断言(真假陈述)。
当然违反了“你不应该实例化这个类的一个项目”的声明,但是如果这是背后的逻辑,那么我们应该到处抛出AssertionError
,这显然不是什么发生。
FWIW,我只是扔了一个
new IllegalStateException("Must not instantiate an element of this class")
这有什么问题吗?在哪种情况下,我应该在自己的代码中抛出 AssertionError
?
对不起,如果这只是一个微妙的疑问,但我在我的代码中经常使用这种模式,我想确保我在做正确的事情。
最佳答案
Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw
AssertionErrors
everywhere, and that is obviously not what happens.
代码并不是说用户不应该调用零参数构造函数。断言是说,就程序员所知,他/她已经不可能调用零参数构造函数(在这种情况下,通过将其设为 private
而不是从 Example
的代码中调用它)。因此,如果发生调用,则该断言已被违反,因此 AssertionError
是合适的。
关于java - 什么是断言错误?在哪种情况下我应该从我自己的代码中抛出它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24863185/