Java Reference
In-Depth Information
deBugging your applications
In the previous section, you debugged a small program while you learned about the kinds of errors,
or bugs, that you will encounter. One technique you saw was using System.out.println() mes-
sages to see what was happening at different points in your program. This is still used a lot, as a
quick‐and‐dirty approach to debugging. But it is not ideal for a number of reasons. For one, it's not
particularly elegant to fill up your code with print statements. It can be messy and you will not only
have to add them in all the places you want to investigate, but you'll also have to carefully remove
them afterward. Other debugging approaches offer more flexibility and functionality. In this sec-
tion, you'll see and use debugger and logger tools to debug better.
using a debugger tool
In the first part of this chapter, you learned about different kinds of errors or bugs. Because the
example problems were small, it was relatively easy to spot the bugs yourself. As your applications
grow, it may become difficult to track down each bug just by looking through the code and outputs,
and even the error messages may not shed sufficient light on the problem. Eclipse and other develop-
ment environments offer debugging tools to support this process. Essentially, a debugger allows you,
the programmer, to execute a program step‐by‐step to see exactly what's happening at each line.
In order to control the debugging process, you need to set breakpoints on particular lines of code.
When the program hits a breakpoint while running in debug mode, the execution will pause so
you can review the current state of the program and the value of the variables at this point in time.
You can then continue to the next breakpoint. This allows you to see exactly where something goes
wrong.
To illustrate the process of debugging using the debugger tool, start from the small retirement fund
program you saw earlier:
public class Errors {
public static void main(String[] args) {
int age = 30;
double retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson";
for (int i = age; i <= 65; i++){
recalculate(retirementFund,0.1);
}
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
public static void recalculate(double fundAmount, double rate){
fundAmount = fundAmount*(1+rate);
}
}
 
Search WWH ::




Custom Search