Appendix C. Debugging

Although there are debugging suggestions throughout the book, we thought it would be useful to organize them in an appendix. If you are having a hard time debugging, you might want to review this appendix from time to time.

The best debugging strategy depends on what kind of error you have:

  • Compile-time errors indicate that there is something wrong with the syntax of the program. Example: omitting the semicolon at the end of a statement.

  • Run-time errors are produced if something goes wrong while the program is running. Example: infinite recursion eventually causes a StackOverflowError.

  • Logic errors cause the program to do the wrong thing. Example: an expression may not be evaluated in the order you expect.

The following sections are organized by error type; some techniques are useful for more than one type.

Compile-Time Errors

The best kind of debugging is the kind you don’t have to do because you avoid making errors in the first place. Incremental development, which we presented in “Writing Methods”, can help. The key is to start with a working program and add small amounts of code at a time. When there is an error, you will have a pretty good idea where it is.

Nevertheless, you might find yourself in one of the following situations. For each situation, we have some suggestions about how to proceed.

The compiler is spewing error messages.

If the compiler reports 100 error messages, that doesn’t mean there are 100 errors in your program. When the compiler encounters ...

Get Think Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.