Testing and Debugging
Program Errors
There are several types of program
errors:
• Compiler errors (syntax errors)
• Runtime errors (program crashes)
• Logic errors
2
Compiler Errors and Warnings
• Syntax errors
• Errors in usage of Java
• Detected by the compiler
• A program with compilation errors cannot be
run
• Warnings
• Warning message generated by the compiler
• The program can be run, but the warnings
must not just be ignored as they might indicate
a problem with the program
3
Compiler Warnings
In Eclipse the following code produces warnings
in the lines marked in red, why?
public static void main(String[] args) {
int i = 1;
int j = 0;
j = j;
[Link]("Program can run");
}
4
Compiler Errors
• Compiler error messages are sometimes hard to
understand because the compiler might detect
the error in a place different from where the error
appears).
• Examples of syntax errors:
• Forgetting a semicolon
• Leaving out a bracket: {,}, (,),[,]
• Redeclaring a variable
• Misspelling a keyword
• Undefined method
• Type mismatch
5
Compiler Errors
The following code has several compilation errors.
Some are relatively easy to find, like missing
semicolons or brackets. Can you find those?
public class CompilerErrors {
public static void main(String[] args) {
int i = 1;
int j;
if (i = 1) {
j=i+2
else j = 0;
for (int i = 0; i < 5; ++i ++j
}
} 6
Compiler Errors
Other errors are a bit harder do find. There are still
two errors in this code. Can you find them?
public class CompilerErrors {
public static void main(String[] args) {
int i = 1;
int j;
if (i = 1) j = i + 2;
else j = 0;
for (int i = 0; i < 5; ++i) ++j;
}
}
7
Compiler Errors
Hints to help find/fix compiler errors:
• Compiler errors are cumulative: when you fix
one, others may go away
• Carefully read the error messages issued by
the compiler
• Realize that the error messages from the
compiler are sometimes confusing as it does
not know what you intended to do.
• Sometimes errors are detected in a different
place from where the error is located.
8
Compiler Errors
Can you explain these two error messages?
public class CompilerErrors2 {
public static void main(String[] args) {
int j; Invalid argument to
for (int i = 0; i < 5; ++i operation ++/--
++j;
}
Syntax error on
}
token “j”, ) expected
9
Compiler Errors
public class CompilerErrors3 {
private int[] a;
public static void main(String[] args) {
a = new int[10]; What is the error here?
}
[Link]("done");
}
10
Confusing Compiler Errors
Why does the compiler print this error message for the last
statement?
public class CompilerErrors3 {
private int[] a;
public static void main(String[] args) {
a = new int[10];
}
[Link]("done");
}
Multiple markers at this line
- Syntax error, insert "SimpleName" to complete QualifiedName
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error on token ".", @ expected after this token
- Syntax error, insert "Identifier (" to complete MethodHeaderName
11
More Compiler Errors
public class CompilerErrors4 {
private static int[] a;
public static void main(String[] args) {
a = new int[]; What is the error here?
}
}
12
More Compiler Errors
public class CompilerErrors5 {
public static void main(String[] args) {
Rectangle r = new Square(7);
Square s = new Rectangle(3, 5);
// Which of these lines will cause
// a compiler error?
}
} Think back to the
lectures about
inheritance
13
More Compiler Errors
public class CompilerErrors6 {
public static void main(String[] args) {
Rectangle r = new Square(7);
int w = [Link]();
int s = [Link]();
// Which of these lines will cause
// a compiler error?
} Think back to the
} lectures about
inheritance
14
Runtime Errors
• Runtime errors: A program runs but
gets an exception error message and it
crashes.
• Runtime errors can be caused by
• Errors in programs or bugs
• Bad or unexpected input
• Hardware or software problems in the
computer system (very rare)
15
Runtime Errors
Hints to help find/fix runtime errors:
• Check the exception message for the
method and line number from which it
came
• Note that the line in the code that caused
the exception may not be the line with the
error
16
Runtime Errors
1 public class RunTimeError {
2 public static void main(String[] args) {
3 int[] nums = new int[10];
4 for (int j = 0; j <= 10; j++)
5 nums[j] = j;
6 }
Description
7 } of error
This code produces this error message:
• Exception in thread "main"
[Link]:
Index 10 out of bounds for length 10 Line and file that
• at [Link]([Link]) caused error
17
Method that caused error
Runtime Errors
1 public class RunTimeError {
2 public static void main(String[] args) {
3 Rectangle[] arr = new Rectangle[10];
4 int counter = 0;
5 for (int j = 0; j < 10; j++)
6 if (arr[j].getLength() == 1)
7 ++counter;
8 [Link](counter);
9 }
10 }
Why is this error message printed?
• Exception in thread "main" [Link]:
Cannot invoke "[Link]()" because "arr[j]" is null
• at [Link]([Link]) 18
Logic Errors
• Logic errors: A program runs without
crashing, but results are not correct
• Logic errors can be caused by:
• Incorrect algorithms. These errors are the
most difficult to fix. It is very important that
you spend sufficient time designing your
algorithms and making sure they are
correct before you implement them in Java.
19
Logic Errors
• Common logic errors are:
• using == instead of a method like equals to
compare the content of objects
• infinite loops
• misunderstanding precedence of
mathematical operators
• starting or ending at the wrong index of an
array
• misplaced parentheses (so code is either
inside a block when it should not be, or
vice versa)
20
Logic Errors
• Try not to declare multiple variables with the same
name, as this might lead to program errors.
• Example:
private int numStudents; // instance variable
…
public void someMethod(){
int numStudents = …; // not the instance variable!
…
}
21
Infinite Loops
• Another kind of runtime error that can occur is an
infinite loop. The program doesn't crash but your
program runs infinitely until you manually stop it.
• Examples:
• int i = 0;
while (i < 100) {
int x = (i + 10) * 25;
}
What are the
• boolean done = false;
problems here?
int a = 25000, b = 0;
while (!done) {
a = a / 10;
if (a < b) done = true;
}
22
Infinite Loops
• Infinite loops can be difficult to detect and debug.
• They most often occur in while loops in which the
condition is always true.
• One way to check for this is by adding a counter to
stop the loop after a large number of iterations.
• boolean done = false;
• int a = 25000, b = 0;
int maxCheck = 10000; // probably big enough
while (!done && maxCheck > 0) {
a = a / 10;
if (a < b) done = true;
maxCheck--;
}
if (maxCheck == 0) [Link]("probably infinite loop");
23
Testing and Debugging
• Testing: to identify any problems before
software is put to use
• “Testing can show the presence of
bugs but can never show their
absence”.
• Debugging: locating bugs and fixing
them
24
Hints for Success
• When writing code:
• Make sure your algorithm is correct before
you start coding.
• Start small:
• Write and test first simpler methods (e.g.
getters, setters, toString)
• Then write and test each of the more
complex methods individually
• Check your code first by a preliminary hand
trace
• Then try running it
25
Debugging Strategies
• Trace or run your code by hand
• When testing add a main method to
each class and invoke from the main
method all other methods to check that
they work as expected. Delete these
main methods once you are done
testing.
• Add print statements to your code
• Use a debugger
26
Tracing by Hand
• Good starting point for small programs or
simple methods
• Keep in mind that sometimes you write code
expecting that the computer will work in a
certain manner, but that might not be how the
computer actually works
• Example: you may think that int i = 9/5;
assigns to i the value 1.8, but it is really 1
• Hint: draw diagrams of reference variables
and the object(s) they are pointing to.
27
Adding a main Method
• Conventionally a main method for purposes
of testing is placed at the end of a class, after
all the other methods
• What are the advantages of having the test
harness (main method) right in a class, rather
than creating another class that is just a test
program?
28
Using Print Statements
• Insert [Link]() statements at key
locations:
• to show values of significant variables
• to show how far your code got before there
was a problem
• In the print statement, it is a good idea to specify
• the location of the trace (the name and line
of a method where the print statement was
added)
• the variable name as well as its value
29
Debuggers
• Integrated Development Environments, like
Eclipse, have an interactive debugger in
which
• You can set breakpoints
• You can single-step step through your code
(one statement at a time)
• You can see what is stored in variables
• You can “watch” a variable or expression
during execution
30
Single step
execution Eclipse Debugger
Variables
Breakpoint
Current statement
31
Eclipse Debugger
• Set a breakpoint
• Execute a program one statement at a time
• Check the values of the variables
32
Defensive Programming
• Write robust programs
• Include checking for exceptional conditions;
try to think of situations that might
reasonably happen, and check for them
• Examples: files that don’t exist, bad input
data
• Generate appropriate error messages, and
either allow the user to reenter the data or exit
from the program
33