Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

In a book, I am reading the author wants to forbid the empty initialization of an object.

class Example {

    private Example() {

        throw new AssertionError();

    }

}

The exception that is thrown here confuses me.

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.

As far as I know, this error is thrown when the assert statement fails. Also, in the Javadoc it is written

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

But I don’t see any assertion being violated here. Of course, the “You shall not instantiate the item of this class” statement has been violated, but if there is the logic behind that, then er should all throw AssertionError s everywhere, and that is obviously not what happens.

For example, I had just thrown a 

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

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

1 Answer

0 votes
by (13.1k points)

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

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

Want to learn Java? Check out the Java certification from Intellipaat.

Browse Categories

...