Java Reference
In-Depth Information
Note In JDK 1.4 you had to specify the -source 1.4 option to the Java compiler in order to enable the
compilation of assertions. In JDK 5 this is no longer required.
By default, assertions are turned off at runtime. This has two major benefits:
AssertionError is an Error , and as such you do not want it thrown in production.
Evaluating the expression in the assertion could be time consuming—having it
switched off by default ensures better performance.
Caution You should never use assertions to perform actions required for the method to work—
assertions should only validate that the values are correct. Since assertions are normally switched off at
runtime, any actions you perform within the assertion will not normally be performed at runtime.
To enable assertions at runtime, you must specify either the -ea or the -enableassertions
command-line option. For example:
java -ea AssertionTest
Without the -ea option, the AssertionTest program will run without errors. With the -ea
option, it will throw an AssertionError .
Assertions can be enabled for individual classes or packages as well, by specifying the
classes or packages on the command line:
java -ea:<packageName> -ea:<className>
Logging
When debugging, you will find it useful to know when you have reached a certain method,
and what the values of some of your parameters and variables are.
In a debugger you might set breakpoints at certain locations and watches on some vari-
ables. But this can be tedious to do each time you want to debug a program.
The next logical step might be to add System.out.println(...); statements throughout
your code. Watching the output in the command window will then give you an idea of what your
program is doing. However, this is not a good idea for code that someone else (your client or
assessor) is deploying: at best it is distracting for them; at worst they may assume that the
“normal” debug messages are signs of an error. In addition, any application that may be
deployed as a server application may not even have a window in which to watch the messages.
And, if something does go wrong with your program, it can be difficult to get the user of the
program to copy the correct messages and send them to you. Furthermore, some of the mes-
sages you want to appear while debugging the application make no sense at deploy time—you
would want to be able to selectively turn off some of the messages.
Search WWH ::




Custom Search