Describe the assert keyword
The programmer assumes certain code while developing when handling exceptions. For example, a number is passed as parameter to a method and it is to be validated whether it is positive. The assumption is to be validated during testing and debugging.
In general, this issue is handled by coding with if like
if(number>0) { // some code }
else { // display error message}
Assertion is helpful for saving time to write code for exception handling. The above coding can be altered by the following:
private void method(int number)
{
assert (number >= 0) //throws an assertion error.
// some code
}
The code assert(number>0) will be passed only when number is positive. An assertion error will be thrown if the value of number is negative.