Page 599 - Introduction to Programming with Java: A Problem Solving Approach
P. 599

                14.6 Two Categories of Exceptions—Checked and Unchecked 565
 public static int getIntFromUser()
{
Scanner stdIn = new Scanner(System.in);
String xStr;
// user entry
boolean valid = false; // is user entry a valid integer?
int x = 0;
// integer form of user entry
System.out.print("Enter an integer: ");
xStr = stdIn.next();
do
{
   }
// end getIntFromUser
}
while (!valid);
try
{
}
}
x = Integer.parseInt(xStr);
valid = true;
catch (NumberFormatException nfe)
{
System.out.print("Invalid entry. Enter an integer: ");
xStr = stdIn.next();
return x;
Apago PDF Enhancer
These initializations before the try block meet the compiler’s demands.
Figure 14.6 Corrected version of the getIntFromUser method
Identifying an Exception’s Category
How can you tell whether a particular exception is classified as checked or unchecked? An exception is an
object, and as such, it is associated with a particular class. To find out if a particular exception is checked
3
or unchecked, look up its associated class on Sun’s Java API Web site. Once you find the class, look at its
ancestors. If you find that it’s a descendant of the RuntimeExeption class, then it’s an unchecked excep- tion. Otherwise, it’s a checked exception.
For example, if you look up NumberFormatException on Sun’s Java API Web site, you’ll see this: java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
java.lang.NumberFormatException
This shows that the NumberFormatException class is a descendant of the RuntimeException class, so the NumberFormatException class is an unchecked exception.
       I
I
f
fy
y
o
o
u
u
s
s
e
ee
e
t
th
h
i
is
                             3 http://java.sun.com/javase/6/docs/api/
sc
cl
la
a
s
ss
s
 i
in
nt
t
h
he
eh
h
i
i
e
e
r
ra
a
r
rc
c
h
hy
y,
,
t
t
h
he
e
  e
ex
xc
ce
ep
p
t
ti
io
o
n
ni
is
s
u
u
n
n
c
c
h
h
e
e
c
ck
ke
ed
d
.
 .
 
   597   598   599   600   601