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.