A.9. Debugging

Professional programmers use sophisticated development environments to debug their programs. While these are beyond the scope of this book, we will mention three useful techniques: compiler error messages, System.out.println() statements, and assertions.

Compiler Error Messages

The Java compiler tries to catch as many errors as possible when compiling our programs. It can be annoying to battle the compiler, but it is much better to find errors at this point than to find them when the program is running. We don't have room to discuss all of the different error messages that arise, but there are a few things to keep in mind:

System.out.println() statements

A common question in debugging is, "What's going on at this line?" We may wish to verify that the program reached a certain line or to examine the values of variables at that point. This is easily done by inserting a System.out.println() statement:

System.out.println("Got to point B. x = " + x);

These statements can often produce far too much output. If this becomes a problem, it may be better to print a message only when something unusual happens:

if (x < 0) { System.out.println("Hey, x is negative!"); }

Be sure to remove these debugging statements before turning in your program.

Assertions

Assertions are a debugging feature which first appeared in Java 1.4. They provide a way of formalizing assumptions that we make in our programs. For example, suppose we assume that some variable x is positive. We can add this statement to our program:

assert x >= 0 : "Hey, x is negative!";

This is just like the previous bit of code, except that:

Exercises

A.22

Add an assertion to the Circle program (Figure A-17) so that the program crashes if the user enters a negative radius.

Категории