什么是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天全站免登陸
全免费A级毛片免费看无码播放