What should we do if the program is not prepared to handle errors by catching exceptions ? We can solve this with assertion statements .
Assertion statements are very useful during the debugging stage of code, and are generally used for errors that the program is not prepared to handle by catching exceptions.
For example: when an error occurs, for example, when an account is traded and the expenditure amount is a positive number or the income amount is a negative number, the program must stop execution immediately. Let the assertion statement work during the debugging code phase, so that you can find some fatal errors. When the program is officially running, you can turn off the assertion statement, but still keep the assertion statement in the source code. If the application needs to be debugged again in the future, you can Re-enable assertion statements.
We use the keyword assert to declare an assertion statement. The assertion statement has the following two formats:
assertbooleanExpression;//An expression that evaluates to a boolean type assertbooleanExpression:messageException;//An expression that evaluates to a string type
When the value is true, program execution continues from the assertion statement.
When the value is false, program execution stops at the assertion statement.
When the value is true, program execution continues from the assertion statement.
When the value is false, the program stops execution from the assertion statement and outputs the value of the messageException expression to remind the user what problem has occurred.
For example, for an assertion statement:
asserti>=0;
If the value of expression i >= 0 is true, the program continues execution; if the value of expression i >= 0 is false, the program ends execution immediately.
When running the application directly using the Java interpreter, assertion statements are turned off by default. You can use -ea to enable assertion statements when debugging the program, for example:
java-eamainclass
For example:
publicclassMain{publicstaticvoidmain(String[]args){int[]score={-120,98,96,94,92};intsum=0;for(intnumber:score){//Use for to traverse the array assertnumber>=0: Negative numbers cannot be grades;sum=sum+number;}System.out.println(total score:+sum);}}
The running results are as follows:
Total Score: 260