






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly.
The first step in debugging is to figure out which kind of error you are dealing with. Although the following sections are organized by error type, there are some techniques that are applicable in more than one situation.
If the compiler reports 100 error messages, that doesn’t mean there are 100 errors in your program. When the compiler encounters an error, it gets thrown off track for a while. It tries to recover and pick up again after the first error, but sometimes it fails, and it reports spurious errors. In general, only the first error message is reliable. I suggest that you only fix one error at a time, and then recompile the program. You may find that
†This appendix appears in Allen B. Downey, How to Think Like a Computer Scientist: Java Version, 2002.
one semi-colon “fixes” 100 errors. Of course, if you see several legitimate error messages, you might as well fix more than one bug per compilation attempt.
First of all, read the error message carefully. It is written in terse jargon, but often there is a kernel of information there that is carefully hidden. If nothing else, the message will tell you where in the program the prob- lem occurred. Actually, it tells you where the compiler was when it noticed a problem, which is not necessarily where the error is. Use the information the compiler gives you as a guideline, but if you don’t see an error where the compiler is pointing, broaden the search. Generally the error will be prior to the location of the error message, but there are cases where it will be somewhere else entirely. For example, if you get an error message at a method invocation, the actual error may be in the method definition. If you are building the program incrementally, you should have a good idea about where the error is. It will be in the last line you added. If you are copying code from a book, start by comparing your code to the book’s code very carefully. Check every character. At the same time, remember that the book might be wrong, so if you see something that looks like a syntax error, it might be. If you don’t find the error quickly, take a breath and look more broadly at the entire program. Now is a good time to go through the whole program and make sure it is indented properly. I won’t say that good indentation makes it easy to find syntax errors, but bad indentation sure makes it harder. Now, start examining the code for the common syntax errors.
B.2 Run-time errors
If a program stops and seems to be doing nothing, we say it is “hanging.” Often that means that it is caught in an infinite loop or an infinite recursion.
Infinite loop
If you think you have an infinite loop and think you know what loop is causing the problem, add a print statement at the end of the loop that prints the values of the variables in the condition, and the value of the condition. For example,
while (x > 0 && y < 0) { // do something to x // do something to y
System.out.println ("x: " + x); System.out.println ("y: " + y); System.out.println ("condition: " + (x > 0 && y < 0)); }
Now when you run the program you will see three lines of output for each time through the loop. The last time through the loop, the condition should be false. If the loops keeps going, you will be able to see the values of x and y and you might figure out why they are not being updated correctly.
Infinite recursion
Most of the time an infinite recursion will cause the program to run for a while and then produce a StackOverflowException. If you suspect that method is causing an infinite recursion, start by checking to make sure that there is a base case. In other words, there should be some condition that will cause the method to return without making a recursive invocation. If not, then you need to rethink the algorithm and identify a base case. If there is a base case, but the program doesn’t seem to be reaching it, add a print statement at the beginning of the method that prints the parameters. Now when you run the program you will see a few lines of output every time the method is invoked, and you will see the parameters. If the parameters are not moving toward the base case, you will get some ideas about why not.
Flow of execution
If you are not sure how the flow of execution is moving through your program, add print statements to the beginning of each method with a message like “en- tering method foo,” where foo is the name of the method. Now when you run the program it will print a trace of each method as it is invoked. It is often useful to print the parameters each method receives when it is invoked. When you run the program, check whether the parameters are reason- able, and check for one of the classic errors—providing parameters in the wrong order.
If something goes wrong during run time, the Java run-time system prints a message that includes the name of the exception, the line of the program where the problem occurred, and a stack trace. The stack trace includes the method that is currently running, and then the method that invoked it, and then the method that invoked that, and so on. In other words, it traces the path of method invocations that got you to where you are. The first step is to examine the place in the program where the error occurred and see if you can figure out what happened.
NullPointerException: You tried to access an instance variable or invoke a method on an object that is currently null. You should figure out what variable is null and then figure out how it got to be that way. Remember that when you declare a variable with an object type, it is initially null, until you assign a value to it. For example, this code causes a NullPointerException:
B.3 Semantic errors
In some ways semantic errors are the hardest, because the compiler and the run-time system provide no information about what is wrong. Only you know what the program was supposed to do, and only you know that it isn’t doing it. The first step is to make a connection between the program text and the behavior you are seeing. You need a hypothesis about what the program is actually doing. One of the things that makes this hard is that computers run so fast. You will often wish that you could slow the program down to human speed, but there is no straightforward way to do that, and even if there were, it is not really a good way to debug. Here are some questions to ask yourself:
In order to program, you need to have a mental model of how programs work. If your program that doesn’t do what you expect, very often the problem is not in the program; it’s in your mental model. The best way to correct your mental model is to break the program into its components (usually the classes and methods) and test each component independently. Once you find the discrepancy between your model and reality, you can solve the problem. Of course, you should be building and testing components as you develop the program. If you encounter a problem, there should be only a small amount of new code that is not known to be correct. Here are some common semantic errors that you might want to check for:
Writing complex expressions is fine as long as they are readable, but they can be hard to debug. It is often a good idea to break a complex expression into a series of assignments to temporary variables. For example:
bobby.setColor (bobby.getColor().darker());
Can be rewritten as
Color bobbyColor = bobby.getColor(); Color darker = bobbyColor.darker (); bobby.setColor (darker);
The explicit version is easier to read, because the variable names provide addi- tional documentation, and easier to debug, because we can check the types of the intermediate variables and display their values. Another problem that can occur with big expressions is that the order of evaluation may not be what you expect. For example, if you are translating the expression 2 xπ into Java, you might write
double y = x / 2 * Math.PI;
That is not correct, because multiplication and division have the same prece- dence, and are evaluated from left to right. So this expression computes xπ/2. A good way to debug expressions is to add parentheses to make the order of evaluation explicit.
double y = x / (2 * Math.PI);
Any time you are not sure of the order of evaluation, use parentheses. Not only will the program be correct (in the sense of doing what you intend); it will also be more readable for other people who haven’t memorized the rules of precedence.
It happens. Even the best programmers occasionally get stuck. Sometimes you work on a program so long that you can’t see the error. A fresh pair of eyes is just the thing. Before you bring someone else in, make sure you have exhausted the tech- niques described here. You program should be as simple as possible, and you should be working on the smallest input that causes the error. You should have print statements in the appropriate places (and the output they produce should be comprehensible). You should understand the problem well enough to describe it concisely. When you bring someone in to help, be sure to give them the information they need.
When you find the bug, take a second to think about what you could have done to find it faster. Next time you see something similar, you will be able to find the bug more quickly. Remember, in this class the goal is not to make the program work. The goal is to learn how to make the program work.