19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1.11 <strong>Programming</strong> Errors 27<br />

Tip<br />

If you don’t know how <strong>to</strong> correct it, <strong>com</strong>pare your program closely, character by character,<br />

with similar examples in the text. In the first few weeks of this course, you will<br />

probably spend a lot of time fixing syntax errors. Soon you will be familiar with <strong>Java</strong><br />

syntax and can quickly fix syntax errors.<br />

fix syntax errors<br />

1.11.2 Runtime Errors<br />

Runtime errors are errors that cause a program <strong>to</strong> terminate abnormally. They occur while a<br />

program is running if the environment detects an operation that is impossible <strong>to</strong> carry out.<br />

Input mistakes typically cause runtime errors. An input error occurs when the program is<br />

waiting for the user <strong>to</strong> enter a value, but the user enters a value that the program cannot handle.<br />

For instance, if the program expects <strong>to</strong> read in a number, but instead the user enters a<br />

string, this causes data-type errors <strong>to</strong> occur in the program.<br />

Another example of runtime errors is division by zero. This happens when the divisor is<br />

zero for integer divisions. For instance, the program in Listing 1.6 would cause a runtime<br />

error, as shown in Figure 1.20.<br />

LISTING 1.6<br />

ShowRuntimeErrors.java<br />

1 public class ShowRuntimeErrors {<br />

2 public static void main(String[] args) {<br />

3 System.out.println(1 / 0);<br />

4 }<br />

5 }<br />

runtime errors<br />

runtime error<br />

Run<br />

FIGURE 1.20<br />

The runtime error causes the program <strong>to</strong> terminate abnormally.<br />

1.11.3 Logic Errors<br />

Logic errors occur when a program does not perform the way it was intended <strong>to</strong>. Errors of this<br />

kind occur for many different reasons. For example, suppose you wrote the program in<br />

Listing 1.7 <strong>to</strong> convert Celsius 35 degrees <strong>to</strong> a Fahrenheit degree:<br />

logic errors<br />

LISTING 1.7<br />

ShowLogicErrors.java<br />

1 public class ShowLogicErrors {<br />

2 public static void main(String[] args) {<br />

3 System.out.println("Celsius 35 is Fahrenheit degree ");<br />

4 System.out.println((9 / 5) * 35 + 32);<br />

5 }<br />

6 }<br />

Celsius 35 is Fahrenheit degree<br />

67

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!