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.

14.3 Point out the problem in the following code. Does the code throw any exceptions?<br />

long value = Long.MAX_VALUE + 1;<br />

System.out.println(value);<br />

14.4 What does the JVM do when an exception occurs? How do you catch an exception?<br />

14.5 What is the prin<strong>to</strong>ut of the following code?<br />

public class Test {<br />

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

try {<br />

int value = 30;<br />

if (value < 40)<br />

throw new Exception("value is <strong>to</strong>o small");<br />

}<br />

catch (Exception ex) {<br />

System.out.println(ex.getMessage());<br />

}<br />

System.out.println("Continue after the catch block");<br />

}<br />

}<br />

What would be the prin<strong>to</strong>ut if the line<br />

int value = 30;<br />

were changed <strong>to</strong><br />

int value = 50;<br />

14.6 Show the output of the following code.<br />

14.3 Exception Types 523<br />

public class Test {<br />

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

for (int i = 0; i < 2; i++) {<br />

System.out.print(i + " ");<br />

try {<br />

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

}<br />

catch (Exception ex) {<br />

}<br />

}<br />

}<br />

}<br />

(a)<br />

public class Test {<br />

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

try {<br />

for (int i = 0; i < 2; i++) {<br />

System.out.print(i + " ");<br />

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

}<br />

}<br />

catch (Exception ex) {<br />

}<br />

}<br />

}<br />

(b)<br />

14.3 Exception Types<br />

Exceptions are objects, and objects are defined using classes. The root class for<br />

exceptions is java.lang.Throwable.<br />

The preceding section used the classes ArithmeticException and InputMismatch-<br />

Exception. Are there any other types of exceptions you can use? Can you define your own<br />

exception classes? Yes. There are many predefined exception classes in the <strong>Java</strong> API. Figure 14.1<br />

shows some of them, and in Section 14.9 you will learn how <strong>to</strong> define your own exception<br />

classes.<br />

Key<br />

Point

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

Saved successfully!

Ooh no, something went wrong!