Intro to Debuggers

(Written largely because newbies in ##java never seem to have this knowledge.)

A “debugger” is a mechanism for monitoring and controlling the execution of your program, usually interactively. Using a debugger, you can stop your program at known locations and examine the actual values of its variables (to compare against what you expected), monitor variables for changes (to see where they got the values they have, and why), and step through code a line at a time (to watch control flow and verify that it matches your expectations).

Pretty much every worthwhile language has debugging support of some kind, whether it's via IDE integration or via a command-line debugger.

(Of course, none of this helps if you don't have a mental model of the “expected” behaviour of the program. Debuggers can help you read, but can't replace having an understanding of the code.)

Debugging Your First Program

Generally, you start running a debugger because you have a known problem -- an exception, or code behaving strangely -- somewhere in your program that you want to investigate more closely. Start by setting a breakpoint in your program at a statement slightly before the problem area.

Breakpoints are instructions to the debugger, telling it to stop execution when the program reaches the statement the breakpoint is set on.

Run the program in the debugger. When it reaches your breakpoint, execution will stop (and your program will freeze, rather than exiting). You can now inspect values and run expressions in the context of your program in its current state. Depending on the debugger and the platform, you may be able to modify those values, too, to quickly experiment with the problem and attempt to solve it.

Once you've looked at the relevant variables, you can resume executing your program - generally in one of five ways:

Whenever the debugger halts your program, you can do any of several things: