什么是AssertionError?在这种情况下,我应该从我自己的代码中抛出? [英] What is an AssertionError? In which case should I throw it from my own code?

查看:39957
本文介绍了什么是AssertionError?在这种情况下,我应该从我自己的代码中抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有效的Java第二版书的第2项中,有这段代码,作者希望禁止对象的空初始化。

In Item 2 of the "Effective Java, 2nd edition" book, there is this snippet of code, in which the author wants to forbid the empty initialization of an object.

class Example {
    private Example() {
        throw new AssertionError();
    }
}

抛出的异常类型是什么让我感到困惑

The type of exception thrown, is what confuses me here.

我不明白如果 AssertionError 只是因为没有更适合的错误而被抛出,或者因为应该是这样的。

I don't understand if the AssertionError is thrown just because of an absence of more suited errors or because it should be this way.

据了解,当 assert 语句失败时,框架会抛出此错误。另外,在javadoc中它只是写了

As I understand, this error is thrown by the framework when an assert statement fails. Also, in the javadoc it's just written


[An AssertionError is]抛出来表示断言失败。

[An AssertionError is] Thrown to indicate that an assertion has failed.

但是我没有看到在这里违反任何断言(true-false statement)。
当然,你不会实例化这个类的项目语句已被违反,但是如果这是背后的逻辑,那么我们应该抛出 AssertionError

But I don't see any assertion (true-false statement) being violated here. 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.

FWIW,我刚刚抛出一个

FWIW, I'd have just thrown a

new IllegalStateException("Must not instantiate an element of this class")

有什么问题吗?在这种情况下,我应该在我自己的代码中抛出一个 AssertionError

Is there something wrong with that? In which case should I throw an AssertionError in my own code?

对不起,如果只是一个微妙的疑问,但是在我的代码中使用这种模式,我想确保我做正确的事情。

Sorry if it's just a subtle doubt but I use this pattern a lot in my code and I want to make sure I'm doing the right thing.

推荐答案


当然,你不会实例化这个类的项目语句已被违反,但如果这是背后的逻辑,那么我们应该抛出 AssertionErrors 无处不在,这显然不是会发生什么。

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.

代码不是说用户不应该调用零args构造函数。这个说法就是说,就程序员而言,他/她已经使得不可能调用零参数构造函数(在这种情况下使它成为 private ,而不是从示例的代码中调用它。因此,如果发生呼叫,则该断言已被违反,因此 AssertionError 是适当的。

The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private and not calling it from within Example's code). And so if a call occurs, that assertion has been violated, and so AssertionError is appropriate.

这篇关于什么是AssertionError?在这种情况下,我应该从我自己的代码中抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆