Java Software Solutions, 8e, Global Edition (Lewis/Loftus)
Chapter 11 Exceptions
11.1 Multiple-Choice Questions
1) A Java program can handle an exception in several different ways. Which of the following is
not a way that a Java program could handle an exception?
A) ignore the exception
B) handle the exception where it arose using try and catch statements
C) propagate the exception to another method where it can be handled
D) throw the exception to a pre-defined Exception class to be handled
E) all of the above are ways that a Java program could handle an exception
2) An exception can produce a “call stack trace” which lists
A) the active methods in the order that they were invoked
B) the active methods in the opposite order that they were invoked
C) the values of all instance data of the object where the exception was raised
D) the values of all instance data of the object where the exception was raised and all local
variables and parameters of the method where the exception was raised
E) the name of the exception thrown
2
© Pearson Education Limited, 2015
Use the code below to answer the following questions. Note that the catch statements in the code
are not implemented, but you will not need those details. Assume filename is a String, x is an int,
a is a double array and i is an int. Use the comments i1, i2, i3, e1, e2, e3, e4, e5 to answer the
questions (i for instruction, e for exception handler).
try
{
BufferedReader infile = new BufferedReader(new FileReader(filename));
// i1
int x = Integer.parseInt(infile.readLine( )); // i2
a[++i] = (double) (1 / x); // i3
}
catch (FileNotFoundException ex) {…} // e1
catch (NumberFormatException ex) {…} // e2
catch (ArithmeticException ex) {…} // e3
catch (ArrayIndexOutOfBounds ex) {…} // e4
catch (IOException ex) {…} // e5
3) An exception raised by the instruction in i1 would be caught by the catch statement labeled
A) e1
B) e2
C) e5
D) either e1 or e5
E) either e1, e4, or e5
4) An exception raised by the instruction in i2 would be caught by the catch statement labeled
A) e1
B) e2
C) e3
D) e5
E) either e2 or e5
5) An exception raised by the instruction in i3 would be caught by the catch statement labeled
A) e2
B) e3
C) e4
D) either e3 or e4
E) either e2, e3, or e4
6) An exception that could also arise in the try statement that does not have an associated catch
statement is
A) ClassNotFoundException
B) IllegalArgumentException
C) NegativeArraySizeException
D) NullPointException
E) OutOfMemoryException
7) A finally clause will execute
A) only if the try statement that precedes it does not throw an exception
B) only if the try statement that precedes it throws an exception that is caught
C) only if the try statement that precedes it throws an exception that is not caught
D) only if the try statement that precedes it throws an exception, whether it is caught or not
E) in any circumstance
8) Which of the following messages passed to the String str could throw a
StringIndexOutOfBoundsException?
A) str.length( )
B) str.charAt(2);
C) str.replace(‘a’, ‘A’);
D) str.equals(str);
E) any of the above could throw a StringIndexOutOfBoundsException
9) The idea that an object can exist separate from the executing program that creates it is called
A) transience
B) static
C) persistence
D) serialization
E) finality
5
© Pearson Education Limited, 2015
For the questions below, use the following skeletal code.
public static void main(String[ ] args)
{
try
{
ExceptionThrowerCode etc = new ExceptionThrowerCode( );
etc.m1( );
etc.m2( );
}
catch (ArithmeticException ae) { … }
}
public class ExceptionThrowerCode
{
…
public void m1( )
{
…
}
public void m2( )
{
try
{
m3( );
}
catch(ArithmeticException ae) {…}
catch(NullPointerException npe) {…}
}
public void m3( )
{
try
{
…
}
catch(ArithmeticException ae) {…}
}
}
10) If an ArithmeticException arises in the try statement in m3
A) it is caught in main
B) it is caught in m1
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminating
11) If a NullPointerException arises in the try statement in m3
A) it is caught in main
B) it is caught in m1
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminating
12) If a NullPointerException arises in the try statement in m1
A) it is caught in main
B) it is caught in m1
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminating
13) NullPointerException and ArithmeticException are both derived from which class?
A) Error
B) Exception
C) RuntimeException
D) IllegalAccessException
E) CheckedException
14) In order to have some code throw an exception, you would use which of the following
reserved words?
A) throw
B) throws
C) try
D) Throwable
E) goto
15) Assume Exceptionname is a checked exception. If a method uses a class that can generate
Exceptionname, then either the method must include try and catch statements where a catch
statement catches Exceptionname, or the method header must include the statement
A) throw Exceptionname
B) throws Exceptioname
C) catch Exceptionname
D) catches Exceptionname
E) implements Exceptionname
16) Which of the following is not true of the RuntimeExceptions class?
A) All RuntimeExceptions throw checked exceptions
B) All RuntimeExceptions are Throwable objects
C) RuntimeException has child classes ArithmeticException and NullPointerException
D) RuntimeException objects are not Error objects
E) All of the above are true
17) Character streams manage
A) byte-sized data
B) binary data
C) Unicode characters
D) ASCII characters
E) compressed data
18) A processing stream is a data stream that
A) can manage both input streams and output streams at the same time
B) performs some manipulation or process on the data
C) can only manage input streams
D) operates on input and output devices but not files
E) can manage byte streams and character streams at the same time
19) System.err is a(n)
A) input stream
B) GUI dialog box that indicates when an error has arisen
C) object
D) Error subclass
E) RuntimeException subclass
20) The Scanner class provides an abstraction for input operations by
A) using try and catch statements to catch any IOException instead of throwing the Exception
elsewhere
B) parsing input lines into individual tokens
C) performing conversion operations from String to the appropriate type as specified in the
Scanner message
D) inputting from the standard input stream if create is called using System.in
E) all of the above
21) The term “exception propagation” means
A) an exception is caught by the first catch clause
B) an exception not caught by the first catch clause is caught by an outer (enclosing) catch clause
C) exceptions are caught, sequentially, by catch clauses in the current try block
D) exceptions always are caught by the outermost try block
E) none of the above
22) Assume infile is a BufferedReader for a textfile and that the textfile is empty. What is
returned from the message infile.readLine( ); ?
A) 0
B) null
C) a special character known as the End-of-file marker (EOF)
D) none of the above, the message causes a NullPointerException to be thrown
E) none of the above, the message causes a EndOfFileException to be thrown
23) Which of the following classes would you use to open a GUI dialog box, which is then used
to select a file to open?
A) JOptionPane
B) JTextArea
C) showOpenDialog
D) JFileChooser
E) JFileReader
24) To implement the KeyListener interface, you must implement all of the following methods
except for which one?
A) keyEvent
B) keyPressed
C) keyTyped
D) keyReleased
E) all of the above methods must be implemented
25) A Timer object generates ________ at regular intervals.
A) ActionEvents
B) MouseEvents
C) RuntimeExceptions
D) non-throwable Exception
E) KeyEvents
26) The Timer object should be used to support which of the following types of applications?
A) animation
B) GUI input from the mouse
C) any applet application
D) input from and output to text files
E) any application that waits for user input via the keyboard
27) When a program terminates because a thrown exception is not handled, the program
A) starts up again automatically
B) opens a dialog box, which asks the user whether the program should start again, end, or enter
a debugging mode
C) saves all output to a disk file called the “runStackTrace.txt”
D) opens a dialog box for the user to specify a disk file name, and all output is stored to that disk
file
E) outputs a message indicating what and where the exception was thrown
28) A method that uses the Scanner class to obtain input does not require either catching or
throwing an IOException. This is because
A) the Scanner class does not call upon any classes that throw checked exceptions
B) the Scanner class’ methods call input methods in try statements and catch IOExceptions so
that they are handled directly in the Scanner class
C) the Scanner class uses JOptionPane dialog boxes instead of java.io classes so that it does not
have to deal with IOExceptions
D) the Scanner class overrides the class IOException making it an unchecked exception
E) none of the above, methods do require handling IOException even if thrown by a method in a
Scanner class
29) The showDialog method is part of which class?
A) JOptionPane
B) JColorChooser
C) JTextArea
D) Scanner
E) all of the above
30) PrintWriter is a better output stream class that PrintStream because PrintWriter
A) has both print and println methods and PrintStream only has print
B) can output both byte and character streams and PrintStream can only output byte streams
C) has error checking mechanisms as part of the class and PrintStream does not
D) will not throw checked exceptions and PrintStream will
E) all of the above
31) The difference between a checked and an unchecked exception is
A) checked exceptions need not be listed in a throws clause
B) unchecked exceptions must be listed in a throws clause
C) neither kind of exception follows the rules of exception propagation
D) an unchecked exception requires no throws clause
E) a checked exception always must be caught by a try block; an unchecked exception does not
32) Which statement is true about BufferedWriters
A) BufferedWriters are used because they improve runtime efficiency
B) BufferedWriters are used because they improve compile time efficiency
C) BufferedWriters can be used with input streams as well as with output streams
D) using a BufferedWriter obviates the necessity for catching IOExceptions
E) none of the above
33) A Swing tool tip is
A) a mechanism to aid the programmer during the creation of the source code for a program
B) a short line of text that appears momentarily when the cursor is rested momentarily on a
component
C) a graphic that appears when the cursor is rested momentarily on a component
D) available to AWT components as well as to Swing components
E) none of the above
34) A disabled component is
A) one that is grayed out
B) one that no longer is active
C) one that is still visually apparent, but no longer functions if clicked
D) provides an indication of functionality that is not currently available
E) all of the above
35) A mnemonic is
A) always a single character
B) can be a collection of characters and/or other keys
C) represents an inactive or disabled component
D) can be used instead of a tool tip
E) none of the above
13
© Pearson Education Limited, 2015
11.2 True/False Questions
1) All run-time Errors throw Exceptions.
2) If an exception is thrown and is not caught anywhere in the program, then the program
terminates.
3) A try statement must have at least one catch statement, but could have many catch statements,
and may or may not have a finally clause.
4) Programmers can define their own Exceptions by extending the Exception class or one of the
descendants of the Exception class.
5) In order to define a keyboard input object, keyboard, you could use the instruction:
BufferedReader keyboard = new BufferedReader(System.in);
6) The following defines a new Exception called AnewException.
public Exception ANewException
{
public ANewException(String message)
{
super(message);
}
}
7) An image (such as a jpg or gif) can be added a JLabel and JButton but not a JTextArea.
8) If an exception arises in a catch statement, and the exception is of the type caught by the catch
statement, then the catch statement catches the same exception. For instance, if the following
catch statement first catches an ArithmeticException and, while executing, throws another
ArithmeticException, it is able to catch the second ArithmeticException as well the first.
catch (ArithmeticException ex) {…}
9) While the Exception class is part of java.lang, IOException is part of java.io.
10) A JTextArea can be used to display text, but not to edit text by the user.
11) A combo box allows the user to select one of several options from a “drop down” menu.
15
12) A combo box generates an item event when the user makes a selection.
13) Scroll panes automatically will scroll vertically, but special code needs to be used if a scroll
pane is to scroll horizontally.
14) The difference between a scroll pane and a split pane is that the former includes a dividing
line while the latter does not.
15) The difference between the throw reserved word and the throws reserved word is that throw
is used within a method body, while throws is used within a method header.
11.3 Free-Form Questions
1) Write code that will create a BufferedReader object to input from standard input (System.in)
an int, a double and a char.
2) Write code with a try statement and proper catch statements to attempt to take the square root
of an int value input using the BufferedReader keyboard. Catch all Exceptions that could
possibly be thrown.
3) Explain or provide an example showing how each of the following Exceptions could arise.
a) ArithmeticException
b) NullPointerException
c) NumberFormatException
d) IndexOutOfBoundsException
e) IOException
4) Rewrite the following code using try and catch statements, catching any exceptions that might
be thrown. Assume keyboard is a BufferedReader.
for (j=0;j<limit;j++)
{
x = Integer.parseInt(keyboard.readLine( ));
y[j] = 1 / x;
}
5) Rewrite the following method using try and catch statements instead of the throws clause in
the method’s header.
public String getInput(String filename) throws IOException
{
BufferedReader infile = new BufferedReader(new FileReader(filename));
String response = infile.readLine( );
infile.close( );
return response;
}
}
6) Test scores should fall between 0 and 100. Assume an Exception called TestScoreException
has been implemented and imported. Write code to input 10 test scores, compute their average,
but throw a TestScoreException in case any inputs violate the proper range. Assume keyboard is
a BufferedReader, already instantiated.
7) Assume that you will want to save, using object serialization, a Student’s name, ssn, major and
minor to a disk file. Write the instance data definitions for Student.
8) Write a save method that will save a given student to the String filename passed as a
parameter.
}
9) Write a set of code that will allow a user to select a file through a JFileChooser, read each
item of the file, outputting each item to the screen, and close the file at the end.
10) Write a set of code that will allow a user to select a file through a JFileChooser and store all
items in the String array list to the selected file, closing the file when done.
11) Write a set of code that will allow a user to select an input image and then place this image in
a JLabel lab1 and add lab1 to a JPanel as the northern component in a JFrame using
BorderLayout. The JFrame has already been instantiated as jf and the BorderLayout already
established. Hint: a JFileChooser returns a File and JLabel requires the String name of a file as
an argument. A File can return its name using File class’ method getAbsolutePath( )
12) Write code to display the contents of the String array stuff to a JTextArea where each
element of the array is placed on individual lines. Assume that no String is more than 25
characters long.
13) Explain how you would use a Timer to create animation in a JLabel.
14) Write a set of code that will create 4 JButtons and add each of these to a JPanel so that they
appear in a 2×2 grid. The JButtons will not have any text appear in them (i.e. no commands or
names) but instead, will each appear as a color set by the user by using JColorChooser.
15) By now you almost certainly have run a Java program that has experienced a
NullPointerException. Explain the reason(s) that a NullPointerException may be generated.
16) What are the three standard I/O streams and what purposes do they fulfill?
17) What is a mnemonic? What are they used for?
18) Why might you want to create your own exception class? What purpose would it serve?