Java Reference
In-Depth Information
waiting for the user to enter a value, but the user enters a value that the program cannot handle.
For instance, if the program expects to read in a number, but instead the user enters a string,
this causes data-type errors to occur in the program.
Another example of runtime errors is division by zero. This happens when the divisor is
zero for integer divisions. For instance, the program in Listing  1.5 would cause a runtime
error, as shown in Figure 1.11.
L ISTING 1.5
ShowRuntimeErrors.java
1 public class ShowRuntimeErrors {
2 public static void main(String[] args) {
3 System.out.println( 1 / 0 );
4 }
5 }
runtime error
Run
F IGURE 1.11
The runtime error causes the program to terminate abnormally.
1.10.3 Logic Errors
Logic errors occur when a program does not perform the way it was intended to. Errors of
this kind occur for many different reasons. For example, suppose you wrote the program in
Listing 1.6 to convert Celsius 35 degrees to a Fahrenheit degree:
logic errors
L ISTING 1.6
ShowLogicErrors.java
1 public class ShowLogicErrors {
2 public static void main(String[] args) {
3 System.out.println( "Celsius 35 is Fahrenheit degree " );
4 System.out.println(( 9 / 5 ) * 35 + 32 );
5 }
6 }
Celsius 35 is Fahrenheit degree
67
You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0 . In Java, the divi-
sion for integers is the quotient—the fractional part is truncated—so in Java 9 / 5 is 1 . To
get the correct result, you need to use 9.0 / 5 , which results in 1.8 .
In general, syntax errors are easy to find and easy to correct because the compiler gives
indications as to where the errors came from and why they are wrong. Runtime errors are not
difficult to find, either, since the reasons and locations for the errors are displayed on the console
when the program aborts. Finding logic errors, on the other hand, can be very challenging. In the
upcoming chapters, you will learn the techniques of tracing programs and finding logic errors.
1.10.4 Common Errors
Missing a closing brace, missing a semicolon, missing quotation marks for strings, and mis-
spelling names are common errors for new programmers.
 
 
Search WWH ::




Custom Search