Assertations vs. Exceptions
They should be distinct, but are often confused.The generally accepted defintion of assertaion is "A statement of something that MUST be true. If it is not, then your program is broken. You cannot recover from a broken program. Fix the bugs!"
An exception, by contrast, is thrown when a condition required for the correct functioning of a method isn't met. An exception may be caught and recovered from.
The concept we're interested in here is the Zen Nature of the condition we're testing. Exceptions and Errors in Java are merely implementation techniques. An assertion may well be implemented with exceptions, but its Zen Nature is not to be caught.
For example, should the user specify a non-existant file, our program may well throw a FileNotFoundException. Clearly we can catch it and ask the user for another file name.
By contrast, should the list of free pages plus the list of used pages not equal the list of all pages, we're screwed. Some fundamental method in our operating system did something wrong and we have no idea of what else might be wrong. So we can't recover.
The intention of assertions is to provide a security check during the writing and debugging of the program. By the time the program is released, no assertions should ever fail. Therefore assertions should be turned off in production.
This in turn implies that we don't care how expensive the assertion is. Excluding any real-time requirements, it is perfectly acceptable for our program to run 10x slower with assertions turned on.
A perfectly adaquate (if ugly) implementation of assertions would be:
if (ASSERTIONS_ENABLED && !condition()) throw new AssertionError("Bad condition");
Because ASSERTIONS_ENABLED would be a constant, the complier can skip the entire statement if it's false. The assertions in Java work much like this, with some really nice advantages.
A very common mistake many programmer make is to use assertions where exceptions should have been used. They then have to release their production code with assertions turned on. The obvious problems are that the code will be slow, it will be harder to read, and the new guy they hired to run the builds will turn them off.
Now, how do you use assertions?A very common mistake many programmer make is to use assertions where exceptions should have been used.