Assertions
Last modified Sunday, 07-Jul-2024 16:06:39 UTC.
- Assertions are used to sanity check programs
- Check that code is doing sane things
- Same idea as always using a default case in switch
- Not for user level errors
- Assertions syntax
- assert <boolean condition> : <error value>
- When running the program, enable assertions with the -ea
flag, e.g.,
java -ea ADodgyProgram
In IntelliJ ...
- Choose Run -> Edit Configurations
- Select the run configuration of interest.
- Click on Modify options link and choose Add VM options.
- Add -ea to the VM options box.
- If the <boolean condition> of an assertion is false
then an error is thrown, and by default the program halts with an
error message containing the <error value>
- Example: Assert.java
Exercises
Exam Style Questions