Reading compiler errors
Everyone writes programs that do not compile. The compiler's messages are precise once you know how to read them. Run this program: it is missing something.
public class Semicolon {
public static void main(String[] args) {
System.out.println("Almost there")
}
}
javac printed Semicolon.java:3: error: ';' expected. Read it from the left:
- the file (
Semicolon.java) and the line (3), - error, then what is wrong: a
;was expected, - the line itself, with a
^under the place where javac noticed the problem.
The editor marks the same place with a red squiggle; hover over it to read the message. javac notices
a missing ; only when it reaches the next thing, so the caret often sits at the end of the line.
When there are several errors, fix the first one and compile again: later errors are often caused
by the first.
This program should print Ada has 3 cats. javac finds two mistakes; fix them one at a time.
public class Pets {
public static void main(String[] args) {
int count = 3
String name = "Ada";
System.out.println(name + " has " + cont + " cats");
}
}
When the program crashes
A program can compile and still fail while it runs. Java then stops it with an exception and prints
a stack trace: the kind of problem, then the methods that were running, innermost first, each with
its file and line. Click a line like Crash.java:7 in the output to jump to it.
public class Crash {
static int share(int total, int people) {
return total / people;
}
public static void main(String[] args) {
System.out.println(share(10, 0));
}
}
The program's exit code is 1: by convention, 0 means success and anything else means failure.