Compile-time, run-time and logic errors
The three families of errors in a Java program: what the compiler refuses, what crashes at run time and what runs but gives a wrong result, including how to read a real javac message.
- 25 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Compile-time error: what is it?
Show the answer
An error the compiler detects before anything runs (syntax, type, unknown symbol, missing return); as long as it remains, the program cannot be launched.
javac gives the file, the line and the message, for instance
B.java:6: error: ';' expected. It gets fixed at the keyboard, before any user ever meets it.javac prints
A.java:8: error: missing return statement, on the closing brace line ofsigne. What is the cause?
```java
static int signe(int n) {
if (n > 0) {
return 1;
} else if (n < 0) {
return -1;
}
}`- If
nis 0, noreturnis reached - A method can hold only one
return, placed on its last line - An
else ifmust always be followed by an emptyelse, even if unneeded - Both
returnstatements are inside blocks, so invisible to the method
Show the answer
If
nis 0, noreturnis reachedThe compiler examines every execution path: for
n == 0, neitherifnorelse ifapplies, and the method ends without a value. javac reports the end of the method, not the faultyif; addingelse { return 0; }settles the case.- If
To produce the .class files, you run the … command; to run the compiled program, you run the … command.
Show the answer
To produce the .class files, you run the javac command; to run the compiled program, you run the java command.
The two steps are separate: a compile-time error prevents the second, a run-time error only shows up in the second.
Syntax error: what is it?
Show the answer
Code that breaks the grammar of the language: a forgotten semicolon, an unclosed parenthesis or brace, a misspelled keyword.
It is a compile-time error: nothing runs.
int x = 3without a semicolon giveserror: ';' expected, with an arrow right after the3.The code
int sum = 7, count = 2; double avg = sum / count;prints3.0instead of3.5. With no error message. Which family is this flaw?- Compile-time: javac should have refused to store an
intin adoublewithout a cast - Run-time: the virtual machine silently swallows an exception during the division
- Logic:
7 / 2is an integer division, computed before the conversion todouble - Warning: javac reports that the result of a
doubleis always approximate
Show the answer
Logic:
7 / 2is an integer division, computed before the conversion todoubleStoring an
intin adoubleis allowed, with no loss. The flaw is upstream: both operands are integers, so the quotient is 3. Converting one operand is enough:(double) sum / count.- Compile-time: javac should have refused to store an