Java Reference
In-Depth Information
Tip
If you don't know how to correct it, compare your program closely, character by char-
acter, with similar examples in the text. In the first few weeks of this course, you will
probably spend a lot of time fixing syntax errors. Soon you will be familiar with Java
syntax and can quickly fix syntax errors.
fix syntax errors
1.11.2 Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. They occur while a
program is running if the environment detects an operation that is impossible to carry out.
Input mistakes typically cause runtime errors. An input error occurs when the program is
waiting for the user to enter a value, but the user enters a value that the program cannot han-
dle. 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.6 would cause a runtime
error, as shown in Figure 1.20.
runtime errors
L ISTING 1.6 ShowRuntimeErrors.java
1 public class ShowRuntimeErrors {
2
public static void main(String[] args) {
3
System.out.println( 1 / 0 );
runtime error
4 }
5 }
Run
F IGURE 1.20
The runtime error causes the program to terminate abnormally.
1.11.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.7 to convert Celsius 35 degrees to a Fahrenheit degree:
logic errors
L ISTING 1.7 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
 
Search WWH ::




Custom Search