Reputation: 1347
I'm preparing for OCP 7, and I encountered this essay on one of that certificate books.
To discourage you from trying to substitute an assertion for an exception, the AssertionError doesn’t provide access to the object that generated it. All you get is the String message.
I tried a lot of possibilities to conduct what is being said but I found no difference on AssertionError
with others.
Can you explain to me what that quote means?
Upvotes: 2
Views: 1667
Reputation: 137329
The explanation can be found in the FAQ in the documentation of the assert
keyword:
Why doesn't an AssertionError allow access to the object that generated it? Similarly, why not pass an arbitrary object from the assertion to the AssertionError constructor in place of a detail message?
Access to these objects would encourage programmers to attempt to recover from assertion failures, which defeats the purpose of the facility.
Consider the following code:
int i = 0;
assert i != 0 : "i must not be zero"
If assertions are enabled, this will throw an AssertionError
with a message initialized to "i must not be zero"
. But that is all this error will contain. If it would contain more information, it would encourage developers to somehow recover from the error by catching the AssertionError
. In theory, it is still possible to inspect the error message and try to do something with it but then you are really going against every good practice.
Upvotes: 3