Java 什么是断言错误?在哪种情况下我应该从我自己的代码中抛出它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24863185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:16:46  来源:igfitidea点击:

What is an AssertionError? In which case should I throw it from my own code?

javaexceptioneffective-java

提问by doplumi

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.

在“Effective Java, 2nd edition”一书的第 2 项中,有一段代码,作者想在其中禁止对象的空初始化。

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

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

抛出的异常类型让我感到困惑。

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

我不明白AssertionError是因为没有更合适的错误而抛出 还是因为它应该是这种方式。

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

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

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

[An AssertionError is] 抛出以指示断言失败。

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.

但我没有看到这里违反了任何断言(真假陈述)。当然违反了“您不应实例化此类的项目”的说法,但如果这是其背后的逻辑,那么我们应该AssertionError到处都抛出s,而这显然不会发生。

FWIW, I'd have just thrown a

FWIW,我刚扔了一个

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

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

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

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.

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

采纳答案by T.J. Crowder

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 AssertionErrorseverywhere, and that is obviously not what happens.

当然违反了“您不应实例化此类的项目”的说法,但如果这是其背后的逻辑,那么我们应该AssertionErrors到处抛出,而这显然不会发生。

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

代码并不是说用户不应该调用零参数构造函数。断言是说,就程序员所知,他/她已经使调用零参数构造函数成为不可能(在这种情况下,通过创建它private而不是从Example的代码中调用它)。因此,如果发生调用,则该断言已被违反,因此AssertionError是适当的。

回答by Henry

The meaning of an AssertionErroris that something happened that the developer thought was impossible to happen.

an 的意思AssertionError是发生了开发人员认为不可能发生的事情。

So if an AssertionErroris ever thrown, it is a clear sign of a programming error.

所以如果 anAssertionError被抛出,这是一个明显的编程错误迹象。

回答by Oliver

An assertion Error is thrown when say "You have written a code that should not execute at all costs because according to you logic it should not happen. BUT if it happens then throw AssertionError. And you don't catch it." In such a case you throw an Assertion error.

当说“你写了一个不应该不惜一切代价执行的代码,因为根据你的逻辑它不应该发生。但是如果它发生了,那么抛出 AssertionError。并且你没有抓住它。”时抛出断言错误。在这种情况下,您会抛出断言错误。

new IllegalStateException("Must not instantiate an element of this class")' // Is an Exception not error.

Note: Assertion Error comes under java.lang.Error And Errors not meant to be caught.

注意:断言错误属于 java.lang.Error 并且错误不打算被捕获。

回答by Raman Gupta

AssertionErroris an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

AssertionError是一个未经检查的异常,它由程序员或 API 开发人员显式引发以指示断言语句失败。

assert(x>10);

Output:

输出:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

如果 x 不大于 10,那么您将收到运行时异常,说 AssertionError。

回答by Matthew McPeak

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionErrorin particular.

我在这里聚会真的很晚,但大多数答案似乎都是关于一般使用断言的原因和时间,而不是AssertionError特别使用。

assertand throw new AssertionError()are very similar and serve the same conceptual purpose, but there are differences.

assertthrow new AssertionError()非常相似并且服务于相同的概念目的,但存在差异。

  1. throw new AssertionError()will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -easwitch).
  2. The compiler knows that throw new AssertionError()will exit the block, so using it will let you avoid certain compiler errors that assertwill not.
  1. throw new AssertionError()无论是否为 jvm 启用断言(即通过-ea开关),都会抛出异常。
  2. 编译器知道这throw new AssertionError()将退出块,因此使用它可以避免某些assert不会的编译器错误。

For example:

例如:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that nhas been initialized by the time the code tries to print it out.

上面的第一个块编译得很好。第二个块不会编译,因为编译器不能保证n在代码尝试打印出来时已经初始化。